3Sum Closest
2015-10-08 21:10
204 查看
3Sum Closest是3Sum的变种
要求找到最接近的那个结果
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.
设立左右两个游标,每次得到结果都和最接近的closest比较一下
要求找到最接近的那个结果
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.
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).
package com.rust.cal; import java.util.Arrays; public class ThreeSumClosest { public static int threeSumClosest(int[] nums, int target) { if (nums.length < 3) { return -1; } int closest = Math.abs(nums[0] + nums[1] + nums[2] - target);//find distance Arrays.sort(nums); int len = nums.length; int res = 0;//nums[0] + nums[1] + nums[2]; for (int i = 0; i < len-2; i++) { if (i > 0 && nums[i] == nums[i-1]) continue;//skip this loop int l = i + 1; int r = len - 1; while (l < r) { int sum = nums[l] + nums[r] + nums[i]; if (closest >= Math.abs(sum-target)) { closest = Math.abs(sum-target); res = sum; } if (sum == target) { return sum; } else if (sum - target > 0) { r--; } else { l++; } } } return res; } public static void main(String args[]){ int[] nums = {1,2,-10,2,2,0,3,5,5,-5,-6,0}; int[] nums1 = {1,1,1}; System.out.println(threeSumClosest(nums,0)); } }
设立左右两个游标,每次得到结果都和最接近的closest比较一下
相关文章推荐
- 剑指offer—求1+2+3+...+n
- java文件读写方法
- UIWebView和WKWebView 改变HTML 图片尺寸 及 字体大小
- C#中的特定类型数组的默认值
- 第2章 变量和基本类型 附2 --声明和定义的区别
- RTSP协议
- leetcode@ [18]4Sum
- Android开发中versionCode和versionName解析
- ListView全行选择
- Cocos2dx控件 Text和TextField
- css3学习之用户界面
- 反省一万次——我为什么这么蠢啊。。。。。。
- 使用Andnroid的post请求
- HDU 1423 裸LCIS
- xeCJK时的警告:xeCJK warning: "CJKfamily-Unknown"
- ArrayList/LinkedList/Vector
- 如何搭建lamp(CentOS7+Apache+MySQL+PHP)环境
- hihoCoder #1162 : 骨牌覆盖问题·三
- 剑指offer—孩子们的游戏(圆圈中最后剩下的数)
- markdown使用LaTeX语法编写数学公式