程序员面试金典——17.12整数对查找
Solution1:针对重复数字的情况题目未做明确说明,虽然此题仍能AC,但有的重复数字用了1次,有的用了超过1次,要求不清晰。重点是这种前后双指针的方法要会!!!
class FindPair {
public:
int countPairs(vector<int> A, int n, int sum) {
// write code here
if(n <= 1)
return -1;
sort(A.begin(), A.end());
int pairs = 0, low = 0, high = n - 1;
while(low < high) {
if (A[low] + A[high] == sum) {
//针对 3,3,3这种情况
if(A[low] == A[high]) {
int x = high - low + 1;
pairs += (x * (x - 1)) / 2;
break;
}
//下面是针对2,2,2,3,4,4,4,4此类情况
int temp_low = A[low], temp_high = A[high], i = 1, j = 1;
while(A[low + 1] == temp_low) {
i++;
low = low + 1;
}
while(high > low && A[high - 1] == temp_high) {
j++;
high = high - 1;
}
pairs += i * j;
low++;
high--;
}
else if (A[low] + A[high] < sum)
low++;
else if(A[low] + A[high] > sum)
high--;
}
return pairs;
}
};