In the set S of n positive integers, find the maximum element m, satisfying m=a + B, where a,b is the element in the set S
Idea 1: First, the set S sort, the time complexity degree nlogn, then the sorted set is hashed, the space complexity n,m from the maximum value of s, and then the inner layer traverses each number of the collection x, to the hash table to detect whether the m-x is in the set, the total time complexity is n*n, the space complexity n
Idea 2: First on the set sorting, time complexity Nlogn, and then the M from the maximum start traversal, A and b take less than m minimum and maximum value, test a+b is equal to M, if small a right move, if the big B left. Total time responsibility for n*n
Reference code:
int find (int s[], int n) {
sort (s, S + N);
for (int i = n-1 I >=2; i.) {
int left = 0, right = i-1;
while (left < right) {
if (S[left] + s[right] = = S[i]) return
s[i];
else if (S[left] + s[right] > s[i])
--right;
else
++left;
}
}
return-1;
}