Leetcode15,16 python 刷题

    xiaoxiao2022-07-13  144

    目录:

    15. 三数之和

    16. 最接近的三数之和

     


    15. 三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]

     利用hash表解决

    class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums_hash={} result=[] for num in nums: nums_hash[num]=nums_hash.get(num,0)+1 if 0 in nums_hash and nums_hash[0]>=3: result.append([0,0,0]) nums=sorted(list(nums_hash.keys())) for i,num in enumerate(nums): for j in nums[i+1:]: if num*2+j==0 and nums_hash[num]>=2: result.append([num,num,j]) if num+j*2==0 and nums_hash[j]>=2: result.append([num,j,j]) dif=0-j-num if dif>j and dif in nums_hash: result.append([num,j,dif]) return result

     16. 最接近的三数之和

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

     

    class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # 如果只有3个数,那直接返回这三个数的和 if len(nums) == 3: return sum(nums) nums = sorted(nums) # 如果最小的和大于目标,那返回最小的和 if sum(nums[:3]) >= target: return sum(nums[:3]) # 如果最大的和小于目标,那返回最大的和 if sum(nums[-3:]) <= target: return sum(nums[-3:]) cur = nums[0] + nums[1] + nums[-1] for i in range(0, len(nums) - 2): # 避免重复计算 if i > 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j < k: res = nums[i] + nums[j] + nums[k] if abs(res - target) < abs(cur - target): cur = res elif res == target: return target elif res < target: j = j + 1 else: k = k - 1 return cur

     

     

    最新回复(0)