leetcode练习题(1)

15. 3Sum


class Solution():
    def threeSum(self, nums):

        if len(nums) < 3:
            return []
        nums.sort()
        answer = set()
        for i in range(0, len(nums)):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            tmp = {}
            for second in nums[i + 1:]:
                if second not in tmp.keys():
                    tmp[-second - nums[i]] = 1
                else:
                    answer.add((nums[i], second, -second - nums[i]))
        return list(answer)

16. 3Sum Closest


class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        nums_len = len(nums)
        closest = sys.maxsize
        for i in range(0, nums_len - 2):
            j = i + 1
            k = nums_len - 1
            while j < k:
                tmp_sum = nums[i] + nums[j] + nums[k]
                difference = tmp_sum - target
                if difference == 0:
                    return tmp_sum
                if abs(difference) < abs(closest - target):
                    closest = tmp_sum
                elif difference < 0:
                    j += 1
                elif difference > 0:
                    k -= 1
        return closest

心得:

  • 这两题的思路类似,都需要先排序,若直接三重循环是会超时的。所以利用两层循环,第二层循环中根据大小的比较来判断下标的变化。
  • 15题中需要保存不重复的列表,故使用了set,且在参考了相关代码之后使用字典来判断能否获得和为零的三个数的组合。

你可能感兴趣的:(leetcode练习题(1))