[LeetCode][JavaScript]3Sum Closest

來源:互聯網
上載者:User

標籤:

3Sum Closest 

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

https://leetcode.com/problems/3sum-closest/

 

 

 

 

與3Sum相同的思路http://www.cnblogs.com/Liok3187/p/4540921.html

每一輪先固定一個數,用雙指標指向數組的頭和尾。

如果目前三個數的和小於target,頭指標++,否則尾指標--,直到指標碰到為止,記錄最接近的結果。

 1 /** 2  * @param {number[]} nums 3  * @param {number} target 4  * @return {number} 5  */ 6 var threeSumClosest = function(nums, target) { 7     var min = Infinity; 8     var res = 0; 9     nums = nums.sort(sorting);10 11     for(var i = 0; i < nums.length - 2; i++){12         if(nums[i - 1] !== undefined && nums[i - 1] === nums[i]){13             continue;14         }15         var curr = nums[i];16         var m = i + 1;17         var n = nums.length - 1;18         while(m < n){19             var tmp = Math.abs(nums[m] + nums[n] + curr - target);20             if(tmp < min){21                 min = tmp;22                 res = nums[m] + nums[n] + curr;23             }24 25             if(nums[m] + nums[n] + curr < target){26                 m++;27             } else {28                 n--;29             }30         }31     }32     return res;33 34     function sorting(a, b){35         if(a > b){36             return 1;37         }else if(a < b){38             return -1;39         }else{40             return 0;41         }42     }43 };

 

 

 

[LeetCode][JavaScript]3Sum Closest

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.