您的位置:首页 > 其它

Leetcode || 3Sum Closest

2015-10-30 12:03 423 查看
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.

在3Sum基础上改改就行

package pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/*
* 求三数和为0,遍历一个数,以它为定点,再转化为2Sum
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
HashSet hs = new HashSet(); //最后不会有重复
int result = 0;
int sum = 0;
int closestDis = Integer.MAX_VALUE;
for(int i=0; i<nums.length; i++) {

int left = i + 1;  //最关键的地方,如果是想办法去掉定点后left=0,会重复计算
int right = nums.length-1;

while(left < right) {
sum = nums[left] + nums[right] + nums[i];
if(sum > target) {
if(sum-target < closestDis) {
closestDis = sum - target;
result = sum;
}
right--;
}
else if(sum < target) {
if(target-sum < closestDis) {
closestDis = target - sum ;
result = sum;
}
left++;
}
else {
return sum;
}
}
}
return result;
}
}

public class Main {
public static void main(String[] args) {
int[] arr = new int[] {1, 1, 1, 0};
System.out.println(new Solution().threeSumClosest(arr, -10));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 3sumclose