LeetCode_16 3SumCloest
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 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. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int sum = nums[0] + nums[1] + nums[2];
int diff = Math.abs(sum - target);
for (int i = 0; i < nums.length - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1])
continue;
int j = i + 1;
int k = nums.length - 1;
while (k > j) {
int aa = nums[i] + nums[j] + nums[k];
int newDiff = Math.abs(aa - target);
if (newDiff < diff) {
diff = newDiff;
sum = aa;
}
if (aa < target) {
j++;
} else {
k--;
}
}
}
return sum;
}
LeetCode_16 3SumCloest的更多相关文章
随机推荐
- Codeforces Round #319 (Div. 2)B. Modulo Sum DP
B. Modulo Sum ...
- POJ 2562:Primary Arithmetic
Primary Arithmetic Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11135 Accepted: 40 ...
- 【OI新闻】2016.10.06
今天有人说好多OJ都狗记邓了- 翻了一下,恭喜以下OJ赢得大奖,获得狗记邓徽章一枚 一等奖Codevs 二等奖Bzoj 三等奖洛谷 后记-感悟 如果正在为OJ发愁的朋友,不要悲伤,不要心急,换一换OJ ...
- 分布式消息中间件Rabbit Mq的了解与使用
MQ(消息队列)作为现代比较流行的技术,在互联网应用平台中作为中间件,主要解决了应用解耦.异步通信.流量削锋.服务总线等问题,为实现高并发.高可用.高伸缩的企业应用提供了条件. 目前市面比较流行的消息 ...
- XML消息解析_php
初识php——微信消息处理 <?php $test = new weixin(); $test->Message(); class weixin{ public function Mess ...
- robotframework - 基础关键词
robotframework基础关键词如下: 1.可在python.notepad++ 编辑: *** Settings *** *** Test Cases ***variable ${a} Set ...
- 为什么要用Go语言做后端
FMZ数字货币量化平台 www.fmz.com, 后端使用Go语言,这里是创始人Zero谈论使用Go语言所带了的便利.原帖地址:https://www.zhihu.com/question/27172 ...
- 【BZOJ4059】Non-boring sequences(分析时间复杂度)
题目: BZOJ4059 分析: 想了半天没什么想法,百度到一个神仙做法-- 设原数列为 \(a\),对于每一个 \(i\) 求出前一个和后一个和 \(a_i\) 相等的位置 \(pre[i]\) 和 ...
- 同余模定理 HDOJ 5373 The shortest problem
题目传送门 /* 题意:题目讲的很清楚:When n=123 and t=3 then we can get 123->1236->123612->12361215.要求t次操作后, ...
- cocos creator 场景如何透明,多个canvas层级显示
转载地址:https://forum.cocos.com/t/creator-canvas/55373/14 Creator 版本:1.7 目标平台:WEB MOBILE 项目需要,页面做了多个Can ...