LeetCode 16 3Sum Closest
2016-05-13 23:36
393 查看
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.
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).
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len = nums.length, flag = Integer.MAX_VALUE; for (int i = 0; i < len - 2; i++) { int left = i + 1, right = len - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; flag = Math.abs(sum - target) < Math.abs(flag) ? sum - target : flag; if (sum < target) left++;//数据小,继续找后边大的数据. else right--;//数据大,继续找前边小的数据. } } return target + flag; }
相关文章推荐
- Linux动态查看网络流量iptraf
- 第4章 创建型模式—工厂方法模式(1)
- GitHub/GitLab创建ssh链接
- 205. Isomorphic Strings
- ISLR第四章分类应用练习题答案
- Spark Top N
- .NET框架
- TextVersion_09_Serializable和Parcelable的区别
- linux下不按回车如何读取字符&&读取到字符不回显
- 【安卓小笔记】android的页面布局
- 用C语言做的一个简单的通讯录
- c语言笔记5之c语言的“单词和语法”
- (2)Java网络-----端口
- linux 驱动函数简介
- 麦子学院PHP工程师课程大纲
- 磁盘中如何清空swap分区,并且加大swap的分区
- hash_map的用法续
- Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探
- Json介绍及Jsoncpp简单使用(测试代码+测试实例)
- Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探