#16 3Sum Closest
来源:互联网 发布:横截面数据是指同一 编辑:程序博客网 时间:2024/04/30 10:23
题目如下:
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 int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len=nums.length; int closet=nums[0]+nums[1]+nums[2]; for(int i=0;i<len-2;i++){ int l=i+1;//left int r=len-1;//right /*if(l==r-1){ closet=Math.abs(closet-target)<Math.abs(nums[i]+nums[l]+nums[r]-target)?closet:nums[i]+nums[l]+nums[r]; continue; }*/ while(l<r-1){ if(closet==target)return closet; int a=nums[i]+nums[l]+nums[r]-target; if(nums[l]+nums[r]<target-nums[i]) l++; else r--; int b=nums[i]+nums[l]+nums[r]-target; if(a*b<0){ int min=Math.abs(a)<Math.abs(b)?a:b; closet=Math.abs(closet-target)<Math.abs(min)?closet:min+target; continue; } } closet=Math.abs(closet-target)<Math.abs(nums[i]+nums[l]+nums[r]-target)?closet:nums[i]+nums[l]+nums[r]; } return closet; }}
public class Solution {public int threeSumClosest(int[] num, int target) {int min = Integer.MAX_VALUE;int result = 0; Arrays.sort(num); for (int i = 0; i < num.length; i++) {int j = i + 1;int k = num.length - 1;while (j < k) {int sum = num[i] + num[j] + num[k];int diff = Math.abs(sum - target); if(diff == 0) return sum; if (diff < min) {min = diff;result = sum;}if (sum <= target) {j++;} else {k--;}}} return result;}}
0 0
- #16 3Sum Closest
- 16 3Sum Closest
- #16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 3Sum Closest
- 16 - 3Sum Closest
- 【16】3Sum Closest
- 16 3sum closest
- LeetCode 16: 3Sum Closest
- LeetCode 16: 3Sum Closest
- leetcode 16 3Sum Closest
- [leetcode 16] 3Sum Closest
- Leetcode【16】:3Sum Closest
- [leetcode 16] 3Sum Closest
- [Leetcode] 16 - 3Sum Closest
- leetcode.16----------3Sum Closest
- jQuery 事件 - blur() 方法
- 第六题
- POJ - 3104 Drying 二分 + 贪心
- 链表的可变数组的实现和一些基本操作
- 有意思 SDWebImage 有两个宏 来判断程序在主线程运行
- #16 3Sum Closest
- 定义一个教师类和一个学生类 第七题
- 堆和栈的区别
- hdu 1237(中缀表达式转后缀并计算)
- hihocoder 1166 期望dp+高斯消元
- 研发管理05:项目管理经验总结
- POJ 2390 解题报告
- JavaScript数组去重、排序以及相关基础操作汇总
- POJ -3253 优先队列 STL