【leetcode-16】3Sum Closest(java)
2015-07-27 13:31
477 查看
问题描述:
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.
分析:该题与leetcode-15及其类似,只是将和为0条件改为了与目标值最小。也即减去目标值的差最接近0.
代码如下:348ms,时间复杂度:O(n2)
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.
[code]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).
分析:该题与leetcode-15及其类似,只是将和为0条件改为了与目标值最小。也即减去目标值的差最接近0.
代码如下:348ms,时间复杂度:O(n2)
[code]public class Solution { public int threeSumClosest(int[] nums, int target) { int left,right; Arrays.sort(nums);//排序 int sum = Integer.MAX_VALUE; int minusWithTarget = Integer.MAX_VALUE; int sumWithTriple; int minus; for(int i = 0;i<nums.length;i++){ if(i-1>=0&&nums[i]==nums[i-1]) continue; left = i+1;right = nums.length-1; while(left<right){ sumWithTriple = nums[i]+nums[left]+nums[right]; minus = sumWithTriple-target; if(minus==0){ return sumWithTriple; }else if(minus>0){ if(minus<minusWithTarget){ minusWithTarget = minus; sum = sumWithTriple; } right--; }else { if(-minus<minusWithTarget){ minusWithTarget = -minus; sum=sumWithTriple; } left++; } } } return sum; } }
相关文章推荐
- Java取得指定年月的最大天数
- [Java]Leetcode69 Sqrt(x)
- Android Stuidio导入Eclipse的工程文件
- java纯数字加密解密实例
- eclipse查看方法说明时出现This element neither has attached source nor attached Javadoc and hence no Javadoc
- Spring 整合ibatis
- Java项目经验
- Java集合框架学习笔记
- mysql java前景
- Spring Batch 文档翻译
- Java ActiveMQ 讲解(一)理解JMS 和 ActiveMQ基本使用
- JAVA线程同步中wait()和notify()简洁例子
- 非常好的javaweb总结
- Struts2 关于返回type="chain"的用法.
- [leetcode-15]3Sum(java)
- 关于java反射的那点事
- Hadoop集群(第7期)_Eclipse开发环境设置
- Struts2 vs SpringMVC for Me
- 读Spring的源代码二:DispatcherServlet处理web请求的过程
- Java生成缩略图Thumbnailator(转载)