LeetCode 3sum-closest 题解

思路

  1. 排序
  2. 枚举一个数a
  3. 双指针移动法确定b和c
  4. 求和,更新最接近的值

复杂度
T ( n ) = O ( n 2 )    M ( n ) = O ( 1 ) T(n)=O(n^2) \; M(n)=O(1) T(n)=O(n2)M(n)=O(1)

class Solution {
    public int threeSumClosest(int[] nums,int target) {
        int sum = nums[0]+nums[1]+nums[2];
        int ans = sum;
        int minDiff = Math.abs(sum-target);
        Arrays.sort(nums);
        int len = nums.length;
        int l;
        int r;
        int diff;
        for (int i = 0; i+3 <= len; ++i) {
            if (nums[i]*3 >= target+minDiff)
                break;
            l = i+1; r = len-1;
            while (l<r) {
                sum = nums[i]+nums[l]+nums[r];
                diff = Math.abs(sum-target);
                if (diff < minDiff) {
                    minDiff = diff;
                    ans = sum;
                }
                if (sum > target)
                    --r;
                else if (sum < target)
                    ++l;
                else
                    return target;
            }
        }
        return ans;
    }
}

Runtime: 10 ms, faster than 85.33% of Java online submissions for 3Sum Closest.
Memory Usage: 37.8 MB, less than 100.00% of Java online submissions for 3Sum Closest.

全部评论

相关推荐

09-29 11:19
门头沟学院 Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务