Exam 29. LeetCode OJ (16)
I finally got the result of my thinking and testing on the last question, so I felt relieved when I encountered this question. This question requires that the sum of the three numbers is the nearest given number,
This is to find the sum of the three numbers in an array so that it is the closest to your target. My idea is to traverse, because it is difficult to guess the result without traversing all the cases.
Do you still have other ways to reduce the number of computations? I guess this method should be feasible if the number and range can be inferred after sorting is possible,
However, if you think about it carefully, it is still quite troublesome. We need to consider a lot of details, because the three numbers we need are not necessarily three consecutive numbers, and we do not
I know how big it is to be "closest". This is also a blind test, so I think I still adopt traversal.
It should be noted that if the sum of the three numbers is equal to the target, then we do not need to continue our work. We can directly return the target.
The code for traversing is as follows:
Class Solution {public: int threeSumClosest (vector
& Nums, int target) {int gap = 0; // gap, that is, the closeness to the target int sum = 0; int len = nums. size (); // number of elements if (len <3) {return-1 ;} // initialize gap sum = nums [0] + nums [1] + nums [2]; gap = target> sum? (Target-sum) :( sum-target); for (int begin = 0; begin <len-2; ++ begin) {if (begin> 0 & nums [begin] = nums [begin-1]) {++ begin; continue;} int pos1 = begin + 1; while (pos1 <len-1) {int pos2 = pos1 + 1; while (pos2 <len) {int tmpsum = nums [begin] + nums [pos1] + nums [pos2]; if (tmpsum = target) {return target;} else if (abs (tmpsum-target) <gap) {sum = tmpsum; gap = abs (tmpsum-target );} ++ pos2 ;}++ pos1 ;}} return sum ;}};
However, I still think it is possible to find the sort method. If anyone knows the idea, please let me know. Thank you. I will continue on my own
Think about it.
Of course, the Traversal method is accepted...