leetcode: 16.最接近的三数之和(双指针)

链接:https://leetcode-cn.com/problems/3sum-closest/
这道题和15题差不多,都是排序+双指针。
C++:

class Solution {
     
public:
    int threeSumClosest(vector<int>& nums, int target) {
     
        sort(nums.begin(),nums.end());
        int ans = nums[0]+nums[1]+nums[2];
        for(int i= 0;i<nums.size()-2;i++)
        {
     
            int j = i+1,k = nums.size()-1;
            while(j<k)
            {
     
                int sum = nums[i]+nums[j]+nums[k];
                if(abs(sum-target)<abs(ans-target))
                    ans = sum;
                if(sum<target)
                    j++;
                else 
                    k--;
            }
        }
        return ans;
    }
};

java:

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-2;i++)
        {
     
            int j = i+1,k = nums.length-1;
            while(j<k)
            {
     
                int sum = nums[i] + nums[j] + nums[k];
                if(Math.abs(target - sum) < Math.abs(target - result))
                    result = sum;
                if(sum > target)
                    k--;
                else if(sum < target)
                    j++;
                else
                    return result;
            }
        }
        return result;
    }
}

Python3:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums, mini = sorted(nums),float('inf')
        for i in range (len(nums)-2):
            j,k = i+1,len(nums)-1
            while j<k:
                s = nums[i]+nums[j]+nums[k]
                if abs(s-target)<abs(mini-target):
                    mini = s
                j,k = j+(s<target),k-(s>=target)
        return mini

你可能感兴趣的:(leetcode,c++,python,leetcode,java)