第16题:3Sum Closest
来源:互联网 发布:如何查询淘宝商品类目 编辑:程序博客网 时间:2024/05/17 08:53
Given an array S of n integers, find three integers inS 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).
题目要求:从已知数组中找出三数之和最接近目标值的三个数(指其绝对值最接近)。
编程语言:javascript
/** * @param {number[]} nums * @param {number} target * @return {number} */var threeSumClosest = function(nums, target) { var length = nums.length; var closest = 9999; //排序 nums.sort(function(x,y) { return x-y; }); for(var i=0; i<length-2; ++i) { if(i>0 && nums[i] == nums[i-1]) { continue; } var left = i+1; var right = length-1; while(left<right) { //记录当前3数和 var current_sum = nums[left] + nums[right] + nums[i]; if(target>current_sum) { if(target-current_sum < closest) { closest = target - current_sum; result_sum = current_sum; } ++left; }else if(target < current_sum) { if(current_sum-target<closest) { closest = current_sum - target; result_sum = current_sum; } --right; }else{ return current_sum; } } } return result_sum; };
0 0
- 【leetcode】第16题:3Sum Closest
- 第16题:3Sum Closest
- leetcode 第16题 3Sum Closest
- leetcode 第15-16题 3Sum & 3Sum Closest
- leetcode第16题——**3Sum Closest
- 【LeetCode】LeetCode——第16题:3Sum Closest
- 第64题 3Sum Closest
- #16 3Sum Closest
- 16 3Sum Closest
- #16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 - 3Sum Closest
- 【16】3Sum Closest
- 16 3sum closest
- Medium 16题 3Sum Closest
- usaco2.1.1-----the castle(flood fill模型)
- POJ 2562 Primary Arithmetic G++
- uboot配置过程(mkconfig脚本+其他)
- android官方training课程
- Win10 卸载 Cortana
- 第16题:3Sum Closest
- Unity3d学习笔记(2)--一个太阳系的实现
- C# 利用Rar压缩文件并FTP上传
- .NET框架-微软C#编程风格官方指南
- SQL学习01
- C++学习记录10--冒泡排序
- svm学习笔记1
- cordova 插件调用activity和结果返回
- 上拉电阻与下拉电阻的作用和区别