leetcode 每日一题 16. 最接近的三数之和

1.暴力法

思路:

遍历枚举出每一种情况,找到最接近的。

代码:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        minCom = abs(nums[0] + nums[1] + nums[2] - target)
        result = nums[0] + nums[1] + nums[2]
        for i in range(len(nums)-2):
            for j in range(i+1,len(nums)-1):
                for k in range(j+1,len(nums)):
                    if abs(nums[i]+nums[j]+nums[k]-target) <minCom:
                        minCom = abs(nums[i]+nums[j]+nums[k]-target)
                        result = nums[i]+nums[j]+nums[k]
                        if minCom == 0:
                            return result
        return result

2.双指针法

思路:

参考第15题三数之和

代码:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        result = nums[0] + nums[1] + nums[2]                
        for i in range(len(nums)-2):
            L = i+1
            R = len(nums)-1
            while L<R:
                threeNumSum = nums[i] + nums[L] + nums[R]
                if abs(threeNumSum-target) < abs(result-target):
                    result = threeNumSum
                if threeNumSum > target:
                    R -= 1
                elif threeNumSum < target:
                    L +=1
                else:
                    return target
        return result

猜你喜欢

转载自www.cnblogs.com/nilhxzcode/p/12792720.html