leetcode-Medium-第12期-陣列-3Sum Closest
摘要:
題目,從陣列中找出三個數的和最接近目標值
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to tar...
題目,從陣列中找出三個數的和最接近目標值
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
- Example
Given array nums = [-1, 2, 1, -4], and target = 1. 最接近的值: (-1 + 2 + 1 = 2).
- 解法
var threeSumClosest = function(nums, target) { const len = nums.length let closest = nums[0] + nums[1] + nums[2] let diff = Math.abs(target - closest) //將陣列按照升序排列 nums = nums.sort((a, b) => a - b); for(let i = 0; i < len - 2; ++i){ let left = i + 1 let right = len -1 while(left < right){ const sum =nums[i] + nums[left] + nums[right] const newDiff = Math.abs(target - sum) if(diff > newDiff){ diff = newDiff closest = sum } if(sum < target){ //和小於目標值,所以將left往右移一個,取得值更大一點(陣列此時為升序 //這樣與目標值的差距會更小一點 left++ }else{ right-- } } } return closest };
- 複習sort
var arr =[ 7,6,15,4,13,2,1] arr.sort() // 1,13,15,2,4,6,7並沒有按照升序 因為無引數按照ascii碼來排序每個元素的第一位,第二位不管。 所以按照升序排列: arr.sort((a,b) => a - b)