016. 3Sum Closest

2016-03-13  本文已影响0人  海湾码农

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

给定一个序列,找出其中三个数,使其和与target最为接近,返回三个数的和。

public class Solution {
  public int threeSumClosest(int[] nums, int target) {
    
    List<Integer> result = new ArrayList<Integer>();
    if (nums == null || nums.length < 3) return 0;
    
    Arrays.sort(nums);
    
    int number = nums[0] + nums[1] + nums[2];
    int closest = Math.abs(number - target);
    
    for (int i = 0; i < nums.length - 2; i++) {
        if (i > 0 && nums[i] == nums[i-1]) continue;
        int left = i + 1;
        int right = nums.length - 1;
        
        while (left < right) {
            int tmp = nums[i] + nums[left] + nums[right];
            if (Math.abs(tmp - target) < closest) {
                number = tmp;
                closest = Math.abs(tmp - target);
            }
            if (tmp > target) right--;
            if (tmp < target) left++;
            if (tmp == target) return tmp;
        }
    }
    return number;
  }
}
上一篇下一篇

猜你喜欢

热点阅读