Leetcode 16 3Sum Closest

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83023198

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.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

这个题和Leetcode15的思路基本类似,就是在前面那个题目的基础上加上了一个判断求值。

1)

import java.util.*;
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        if(len < 3){
            return 0;
        }
        int Min = nums[0] + nums[1] + nums[2];
        for(int left = 0 ; left < len - 2 ; left++){
            int mid = left + 1;
            int right = len - 1;
            while(mid < right){
                int tmp = target - nums[left];
                if(Math.abs(Min - target) > Math.abs(tmp - nums[mid] - nums[right]))
                    Min = nums[mid] + nums[left] + nums[right];
                if(nums[mid] + nums[right] == tmp){
                    return target;
                }else if(nums[mid] + nums[right] < tmp){
                    mid++;
                }else{
                    right--;
                }
            }
        }
        return Min;
    }
}

时间复杂度:O(n2)

猜你喜欢

转载自blog.csdn.net/Neo233/article/details/83023198