码迷,mamicode.com
首页 > 其他好文 > 详细

3Sum Closest

时间:2015-12-24 20:41:40      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

 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 };

 

3Sum Closest

标签:

原文地址:http://www.cnblogs.com/HuoAA/p/5074229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!