3Sum Closest

 1 var threeSumClosest = function(nums, target) {
 2     if (nums.length < 3) {
 3         return -1;
 4     }
 5 
 6     nums = nums.sort(function(num1, num2) {
 7         return num1 - num2;
 8     });
 9 
10     console.log(nums);
11 
12     var i, l, r, sum, ret, first = true;
13 
14     for (i = 0; i < nums.length - 2; i++) {
15         l = i + 1;
16         r = nums.length - 1;
17 
18         while (l < r) {
19             sum = nums[i] + nums[l] + nums[r];
20 
21             if (first) {
22                 ret = sum;
23                 first = false;
24             } else {
25                 if (Math.abs(sum - target) < Math.abs(ret - target)) {
26                     ret = sum;
27                 }
28 
29                 if (sum === target) {
30                     return target;
31                 } else if (sum > target) {
32                     r--;
33                 } else {
34                     l++;
35                 }
36             }
37         }
38     }
39 
40     return ret;
41 };

 

posted @ 2015-12-24 20:30  叫我霍啊啊啊  阅读(215)  评论(0编辑  收藏  举报