Leetcode 16. Python implementation of the closest sum of three numbers

Time:2021-2-27
  • Title Requirements:

Leetcode 16. Python implementation of the closest sum of three numbers

  • Thinking:

    • Sort the array, traverse the array, use double pointer to find all the elements after the current element, the current element and the two elements closest to the target value target, and return the sum of three numbers as res
  • Core code:
#Sort the array
nums.sort()
#The result is initialized to the sum of the first three elements of the array
res = nums[0] + nums[1] + nums[2]
#Traversing arrays
for i in range(len(nums)-2):
    left = i + 1
    right = len(nums) - 1
    while left < right:
        tmp = nums[i] + nums[left] + nums[right]
        #If the sum of the current three elements is closer to the target value, assign the sum of the current three elements to the result res
        if abs(tmp - target) < abs(res - target):
            res = tmp
        if tmp < target:
            left += 1
        else:
            right -= 1
return res
  • Full code:
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        if len(nums) < 3:
            return 0
        nums.sort()
        res = nums[0] + nums[1] + nums[2]
        for i in range(len(nums)-2):
            left = i + 1
            right = len(nums) - 1
            while left < right:
                tmp = nums[i] + nums[left] + nums[right]
                if abs(tmp - target) < abs(res - target):
                    res = tmp
                if tmp < target:
                    left += 1
                else:
                    right -= 1
        return res

Recommended Today

Redis design and implementation 4: Dictionary Dict

In redis, the dictionary is the infrastructure. Redis database data, expiration time and hash type all take the dictionary as the underlying structure. Structure of dictionary Hashtable The implementation code of hash table is as follows:dict.h/dictht The dictionary of redis is implemented in the form of hash table. typedef struct dictht { //Hash table array, […]