Chap5: question 35 - 37

时间:2023-02-02 11:54:59

35. 第一个只出现一次的字符

char firtNotRepeat(char *s)
{
if(s == NULL) return 0;
int i = 0;
while(s[i] != '\0') record[s[i++]] ^= 1;
i = 0;
while(!record[s[i]]) ++i;
return s[i];
}

36.数组中的逆序对个数 (归并排序解法)

#include <iostream>
using namespace std;
void inversePairsCore(int data[], int copy[], int low, int high, int& count)
{
if(low == high) return; int mid = (low + high) / 2;
inversePairsCore(data, copy, low, mid, count);
inversePairsCore(data, copy, mid+1, high, count); int k = high, tag_mid = mid, tag_high = high;
while(low <= mid && tag_mid +1 <= high)
{
if(data[mid] > data[high])
{
copy[k--] = data[mid--];
count += high - tag_mid;
}
else if(data[mid] < data[high])
{
copy[k--] = data[high--];
}
else
copy[k--] = data[high--];
}
while(low <= mid) copy[k--] = data[mid--];
while(tag_mid+1 <= high) copy[k--] = data[high--]; for(k = low; k <= tag_high; ++k)
data[k] = copy[k];
}
int inversePairs(int data[], int length)
{
if(data == NULL && length < 1) return 0; int *copy = new int[length];
int count = 0;
inversePairsCore(data, copy, 0, length-1, count); delete[] copy;
return count;
} int main()
{
int data[] = {4, 4, 4, 3, 3};
printf("%d\n", inversePairs(data, sizeof(data)/4));
return 0;
}

37.  两个链表的第一个公共结点

int getLength(ListNode *pHead)
{
if(pHead == NULL) return 0;
int len = 0;
ListNode *p = pHead;
while(p != NULL)
{
p = p->next;
len ++;
}
return len;
}
ListNode* firstNode(ListNode *pHead1, ListNode* pHead2)
{
if(pHead1 == NULL || pHead2 == NULL) return NULL;
int len1 = getLength(pHead1);
int len2 = getLength(pHead2);
if(len1 < len2) return firstNode(pHead2, pHead1);
int k = len1 - len2;
ListNode *p1 = pHead1, *p2 = pHead2;
while(k > 0)
{
p1 = p1->next;
--k;
}
while(p1 != NULL && p2 != NULL && p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
if(p1 == NULL || p2 == NULL) return NULL;
return p1;
}

Chap5: question 35 - 37