Title (Lintcode):
1. The sum of two
2. The sum of three
3. The sum of the closest three numbers
4. The sum of four
Take the sum of three numbers as an example:
A
The common algorithm, multiple traversal arrays, requires multiple for nesting, but severely timed out.
Two
In the outer cycle, there is no "impossible to meet the requirements" situation.
For example, in the sum of three numbers, if the sum of two numbers is greater than 0, a direct break. But the question does not say that there will be no negative, so wrong.
Three
Then (ii), the sum of two numbers is greater than 0 is invalid, because the array is unordered, so first sort
sort (Nums.begin (), Nums.end ());
You can then break off when the guarantee is greater than 0 o'clock. Like this:
for (int0; i < nums.size (); i++) { if0break; for (int j = i;j < Nums.size (); j + +) { if00break ; for (int k = j; k < Nums.size (); k++) {
Four
Set two pointers, point to "Array header" (front) and "End of Array" (rear), calculate the sum of the two pointers, plus a number for the For loop, and get three numbers and sum:
If sum is greater than 0, make and become smaller, rear--can be, if sum is less than 0, make and become larger, front++ can be.
vector<vector<int> > Threesum (vector<int> &nums) { Set<vector<int> >re; Vector<int>inch; Sort (Nums.begin (), nums.end (), Greater<int>()); intfront, rear, sum; for(inti =0; I < nums.size (); i++) {Front=0; Rear= Nums.size ()-1; while(Front <rear) { if(Front = = i) front++; Else if(Rear = = i) rear--; if(front = = rear) Break; Sum= Nums[front] + nums[rear] +Nums[i]; if(Sum = =0) { inch. Clear (); inch. Push_back (Nums[front]); inch. Push_back (Nums[rear]); inch. Push_back (Nums[i]); Sort (inch. Begin (),inch. End ()); Re.insert (inch); Do{front++;} while(Front < rear && Nums[front] = = Nums[front-1]); } Else if(Sum >0) front++; Elserear--; } } returnVector <vector<int>>(Re.begin (), Re.end ()); }
Two pointers--reducing array loops