3Sum Closest Leetcode

来源:互联网 发布:淘宝账期延长十五天 编辑:程序博客网 时间:2024/06/11 03:59

Given an array S of n integers, find three integers inS 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).


Seen this question in a real interview before?  
Yes
N


My solution:

import java.util.Arrays;class Solution {    public int threeSumClosest(int[] nums, int target) {    Arrays.sort(nums);    int result = nums[0] + nums[1] + nums[2];        for(int i = 0; i < nums.length; i++) {        int x = 0;        int y = nums.length - 1;        int twoNumAddTarget = target - nums[i];        while(x < y - 1) {        if (nums[x] + nums[y] < twoNumAddTarget) {        x ++;        } else {        y --;        }                        if (x == i) {        x ++;        } else if (y == i) {        y --;        }                if (x >= y) {        break;        }                        if (Math.abs(nums[i] + nums[x] + nums[y] - target) < Math.abs(target - result)) {            result = nums[i] + nums[x] + nums[y];            }        }        }        return result;        }}


原创粉丝点击