[LeetCode] 3Sum Closest
2014-11-17 13:50
309 查看
Given an array of 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).
Ideas: same with the 3sum, use two value to store the min difference and the min sum
public class Solution {
public int threeSumClosest(int[] num, int target) {
int minDiff = Integer.MAX_VALUE;
int minValue = Integer.MAX_VALUE;
int length = num.length;
Arrays.sort(num);
for(int i = 0; i < length - 2; i++)
{
int start = i + 1;
int end = length - 1;
while(start < end)
{
int sum = num[i] + num[start] + num[end];
int dif = Math.abs(sum - target);
if(dif == 0 ){
return target;
} else if(dif < minDiff){
minDiff = dif;
minValue = sum;
}
if(sum <= target){
start++;
}else{
end--;
}
}
}
return minValue;
}
}
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).
Ideas: same with the 3sum, use two value to store the min difference and the min sum
public class Solution {
public int threeSumClosest(int[] num, int target) {
int minDiff = Integer.MAX_VALUE;
int minValue = Integer.MAX_VALUE;
int length = num.length;
Arrays.sort(num);
for(int i = 0; i < length - 2; i++)
{
int start = i + 1;
int end = length - 1;
while(start < end)
{
int sum = num[i] + num[start] + num[end];
int dif = Math.abs(sum - target);
if(dif == 0 ){
return target;
} else if(dif < minDiff){
minDiff = dif;
minValue = sum;
}
if(sum <= target){
start++;
}else{
end--;
}
}
}
return minValue;
}
}
相关文章推荐
- leetcode 3Sum Closest
- [LeetCode 16] 3Sum Closest
- [leetcode 16] 3Sum Closest
- leetcode 3Sum Closest
- leetcode question 16: 3Sum Closest
- LeetCode 3Sum Closest
- [leetcode] 3Sum Closest
- LeetCode 3Sum Closest
- leetcode16. 3Sum Closest
- leetcode 57: 3Sum Closest
- leetCode#16. 3Sum Closest
- Leetcode题解-3Sum&3Sum Closest
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- 《leetCode》:3Sum Closest
- C#解leetcode 16. 3Sum Closest
- leetcode -- 3Sum Closest
- [LeetCode][JavaScript]3Sum Closest
- leetcode 16. 3Sum Closest
- [LeetCode]3Sum Closest
- [Leetcode] 3sum-closest 给定值,最为相近的3数之和