leetcode 16. 3Sum Closest
2016-05-04 14:53
197 查看
import java.util.Arrays; //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). public class Solution { public static void main(String[] args) { int[] a = {1,1,1,1}; int result = threeSumClosest(a,-100); System.out.println(result); } public static int threeSumClosest(int[] nums, int target) { int result = 0; int cha = 1000; Arrays.sort(nums); //先对数组排序 for(int i = 0;i<nums.length-2;i++){ //与上一题差不多,遍历数组,从当前元素之后的元素段首尾相加:1(当前),1(首),1,1(尾) int j = i+1; int end = nums.length-1; while(j<end){ //首小于尾时循环 if(nums[i]+nums[j]+nums[end] == target){ return target; }else if(nums[i]+nums[j]+nums[end]<target){ //根据三数相加与target的差值调整首尾的位置 if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){ cha = Math.abs(target-nums[i]-nums[j]-nums[end]); result = nums[i]+nums[j]+nums[end]; } j++; }else{ if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){ cha = Math.abs(target-nums[i]-nums[j]-nums[end]); result = nums[i]+nums[j]+nums[end]; } end--; } } } return result; } }
相关文章推荐
- MYSQL必知必会读书笔记 第四章 检索数据
- ubuntu上运行eclipse出现 Call From master to localhost:9000 failed on connection exception
- ubuntu14.04 ibus 输入法框架
- 关于“==”和equals()的比较
- PS 魔法棒
- C# 合并两个数组总结
- osg中漫游器的原理——osgGA::CameraManipulator(二)
- java遍历文件目录并排序
- Jmeter日志输出和日志级别设置
- iOS之UITextField怎么自定义键盘的return键
- 文件上传与下载
- 关于opencv打不开图片或者视频
- css自定义字体font-face的兼容和使用
- java Atomic原子更新
- Android 网络请求,应用的下载与安装
- MyEclipse 快捷键
- 过滤器 拦截器 监听器 简单介绍
- SQL批量删除表、数据
- POJ 1789 Truck History 最小生成树
- AppDomain 详解