您的位置:首页 > 其它

3Sum Closest

2015-10-08 21:10 204 查看
3Sum Closest是3Sum的变种

要求找到最接近的那个结果

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).


package com.rust.cal;

import java.util.Arrays;

public class ThreeSumClosest {
public static int threeSumClosest(int[] nums, int target) {
if (nums.length < 3) {
return -1;
}
int closest = Math.abs(nums[0] + nums[1] + nums[2] - target);//find distance
Arrays.sort(nums);
int len = nums.length;
int res = 0;//nums[0] + nums[1] + nums[2];
for (int i = 0; i < len-2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;//skip this loop
int l = i + 1;
int r = len - 1;
while (l < r) {
int sum = nums[l] + nums[r] + nums[i];
if (closest >= Math.abs(sum-target)) {
closest = Math.abs(sum-target);
res = sum;
}
if (sum == target) {
return sum;
} else if (sum - target > 0) {
r--;
} else {
l++;
}
}
}
return res;
}

public static void main(String args[]){
int[] nums = {1,2,-10,2,2,0,3,5,5,-5,-6,0};
int[] nums1 = {1,1,1};
System.out.println(threeSumClosest(nums,0));
}
}


设立左右两个游标,每次得到结果都和最接近的closest比较一下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: