LeetCode题解 -- 双指针(16)

3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

时间复杂度:O(n^2)
空间复杂度:O(1)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int length = nums.length;
        if(length < 3)
            return -1;
        int result = 0;
        int minDiff = Integer.MAX_VALUE;
        Arrays.sort(nums);

        for(int i = 0;i < length;i++){
            int start = i + 1;
            int end = length - 1;
            while(start < end){
                int tempSum = nums[i] + nums[start] + nums[end];
                if(tempSum == target){
                    return tempSum;
                }
                if(Math.abs(tempSum - target) < minDiff){
                    minDiff = Math.abs(tempSum - target);
                    result = tempSum;
                }
                if(tempSum - target > 0){
                    end--;
                }else{
                    start++;
                }
            }
        }
        return result;
    }
}
发布了30 篇原创文章 · 获赞 0 · 访问量 879

猜你喜欢

转载自blog.csdn.net/fantow/article/details/104672851