3Sum Closest: Find the sum of the three numbers in the sequence that is Closest to the given value.
That is, find min {target-a-B-c} a, B, c blog to Set S;
(1) The simplest way is to find all the three distinct numbers and save them to the set, and then use target, target (+/-) I, I [0...]
The complexity is basically O (n ^ 3 ).
Int threeSumClosest (vector
& Num, int target) {int n = num. size (); if (n <3) return 0; unordered_set
Sum; for (int I = 0; I
(2) with a simple solution, we need to optimize it.
(1) A triple loop can certainly be killed, that is, first store the subscript of the two numbers and their corresponding to the map.
(2) map the map with the number of arrays. The first is a [I] + 0, then a [I] + 1, which is increased in sequence and will always be found.
(3) This is basically O (N ^ 2.
int threeSumClosest(vector
&num, int target) { int n=num.size(); if(n<3) return 0; unordered_map
> num0; for(int i=0 ; i