CareerCup Google Interview 找到两个数的差为一个特定数
Given an integer 'k' and an sorted array A (can consist of both +ve/-ve nos), output 2 integers from A such that a-b=k.
PS:
nlogn solution would be to check for the occurence of k-a[i] (using binary search) when you encounter a[i]. methods like hash consume space.
Is an O(n) solution with O(1) extraspace possible?
http://www.careercup.com/question?id=9449188
利用2sum的思想,设定两个指针。由于2sum是在数组两端设定指针,而对于difference,在两端设定指针当a[j] - a[i] > key时, j--或者i++都会令a[j]-a[i]的差变小,不具有唯一性。
所以最开始设定指针都在同一端,这样a[j]-a[i]>key时,只有i++一个操作能令差变小。同样a[j]-a[i]<key时,也只有j++能令差变大。当指针相遇,或者j==a.size()时说明没有解。同时,由于数组中可能有负数,且key可能为负数,所以用abs(key)来进行比较。
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 void solve(vector<int> &a, int key) 6 { 7 if (a.size() <= 1) 8 { 9 cout << "No answer!" << endl; 10 return; 11 } 12 13 int i = 0; 14 int j = 1; 15 16 key = abs(key); 17 18 while(i < j && j < a.size()) 19 { 20 if (a[j] - a[i] == key) 21 { 22 cout << a[j] << ' ' << a[i] << endl; 23 return; 24 } 25 else if (a[j] - a[i] > key) 26 { 27 i++; 28 } 29 else 30 { 31 j++; 32 } 33 } 34 35 cout << "No answer!" << endl; 36 } 37 38 int main() 39 { 40 vector<int> a; 41 for(int i = 0; i < 10; i++) 42 a.push_back(i); 43 44 solve(a, 1); 45 solve(a, 2); 46 solve(a, 9); 47 solve(a, 10); 48 solve(a, -1); 49 }