LeetCode16.最接近的三数之和 JavaScript
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 答案参考
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
nums=nums.sort(function(a,b){return a-b})
var i=0;
var num=nums[0]+nums[1]+nums[2];
var and=num
for(var i=0;i<nums.length-2;i++){//和三数之和一样,我先用的while循环,现在用的
//for循环
var k=nums.length-1
for(var j=i+1;j<nums.length-1&&j!=k;){
sum=nums[i]+nums[j]+nums[k];
if(Math.abs(target-sum)<=Math.abs(target-and)){
and=sum
num=Math.abs(target-sum)
}
if(target-sum>0){
j++;
}
else{
k--
}
}
}
return and };
LeetCode16.最接近的三数之和 JavaScript的更多相关文章
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数  while (l < r && nums[r] == nums[--r ...
- Leetcode题库——16.最接近的三数之和
@author: ZZQ @software: PyCharm @file: threeSumClosest.py @time: 2018/10/14 20:28 说明:最接近的三数之和. 给定一个包 ...
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- lintcode-59-最接近的三数之和
59-最接近的三数之和 给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和. 注意事项 只需要返回三元组之和,无需返回三元组本身 样例 例如 S = ...
- LeetCode:最接近的三数之和【16】
LeetCode:最接近的三数之和[16] 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这 ...
- Java实现 LeetCode 16 最接近的三数之和
16. 最接近的三数之和 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存 ...
随机推荐
- [转]How to use IHttpContextAccessor in static class to set cookies
本文转自:http://stackoverflow.com/questions/37329354/how-to-use-ihttpcontextaccessor-in-static-class-to- ...
- 一个C#后台调用接口的例子
string url = ConfigurationSettings.AppSettings["resurl"].ToString(); var wc = new WebClien ...
- Error creating bean with name 'com.cloud.feign.interfaces.xxxFeignClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalSt.PathVariable annotation was empty on
环境: Spring Cloud:Finchley.M8 Spring Boot:2.0.0.RELEASE 报错信息: Error creating bean with name 'com.clou ...
- input文本框点击第一次光标在最右边
效果: 样式效果引入bootstrap4.0就OK了. HTML代码: <div class="input-group w-25"> <div class=&qu ...
- nodejs进阶(7)—async异步流程控制
Async介绍 Async是一个流程控制工具包,提供了直接而强大的异步功能.基于Javascript为Node.js设计,同时也可以直接在浏览器中使用. Async提供了大约20个函数,包括常用的 m ...
- XMLHttpRequest.responseType
"arraybuffer" "blob" "document" "json" "text"
- freebsd mount linprocfs
mount用来做什么? to prepare and graft a special device or the remote node(rhost:path) on to the file syst ...
- Java NIO(四) Scatter/Gather
Java NIO开始支持scatter/gather,scatter/gather用于描述从Channel(译者注:Channel在中文经常翻译为通道)中读取或者写入到Channel的操作.分散(sc ...
- 【Leetcode】【Medium】Single Number
Given an array of integers, every element appears twice except for one. Find that single one. Note:Y ...
- python入门3 python变量,id(),is运算符
python变量无需声明数据类型,可以直接赋值使用. 比如: num=100 #整数 str="字符串" #字符串 turple1 =('mon','tue','wed','thu ...