/********************************************** Function:input two array and find the kth value the run time cost is O(log(m+n)) **********************************************/ int find_kth(int A[],int m,int B[],int n,int k) { if(m > n) return find_kth(B,n,A,m,k); if(m == 0) return B[k-1]; if(k == 1) return min(A[0],B[0]); int pa = min(k/2,m); int pb = k - pa; if(A[pa-1] < B[pb-1]) return find_kth(A + pa,m - pa,B,n,k - pa); else if(A[pa-1] > B[pb-1]) return find_kth(A,m,B + pb,n - pb,k - pb); else return A[pa-1]; } //无序数组最长的连续 int longestConsecutive(int A[],int len) { std::unordered_map<int,bool> used; for(int i=0;i<len;i++) used[A[i]] = false; int longest = 0; for(int i=0;i<len;i++) { if(used[A[i]]) continue; int length = 1; for(int j=A[i]+1;used.find(j) != used.end();j++) { used[j] = true; length++; } for(int j=A[i]-1;used.find(j) !=used.end();j--) { used[j] = true; length++; } longest = max(length,longest); } return longest; } //two Sum std::pair<int,int> twoSum(int A[],int len,int target) { std::pair<int, int> result; std::unordered_map<int,int> m; for(int i=0;i<len;i++) { m[A[i]] = i; } for(int i=0;i<len;i++) { int gap = target - A[i]; if(m.find(gap) != m.end()) { result.first = i+1; result.second = m[gap]+1; break; } } return result; }
时间: 2024-10-01 05:03:00