`
frank-liu
  • 浏览: 1666034 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

leetcode: 3Sum Closest

 
阅读更多

问题描述:

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

原问题链接:https://leetcode.com/problems/3sum-closest/

 

问题分析

    这个问题的思路和前面3sum的过程很接近。就是首先对数组排序,然后取target和里面取一个数的差。再到数组里去查找比较和这个差接近的值。如果相等的话就直接返回,否则记录它们的和与target值的偏差,记录下来偏差最小的那个返回。

    详细的实现代码如下:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = 0, dif = Integer.MAX_VALUE;
        for(int i = 0; i < nums.length - 2; i++) {
            int l = i + 1, r = nums.length - 1;
            while(l < r) {
                if(nums[l] + nums[r] == target - nums[i]) return target;
                else if(nums[l] + nums[r] < target - nums[i]) {
                    if(target - nums[i] - nums[l] - nums[r] < dif) {
                        dif = target - nums[i] - nums[l] - nums[r];
                        result = nums[l] + nums[r] + nums[i];
                    }
                    l++;
                } else {
                    if(nums[l] + nums[r] + nums[i] - target < dif) {
                        dif = nums[l] + nums[r] + nums[i] - target;
                        result = nums[l] + nums[r] + nums[i];
                    }
                    r--;
                }
            }
        }
        return result;
    }
}

     总体的时间复杂度为O(N * N)。这里要注意的是实现的细节里取的索引值的范围。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics