您现在的位置是:主页 > news > 衡水市建设局网站/西安seo哪家好
衡水市建设局网站/西安seo哪家好
admin2025/6/8 7:58:16【news】
简介衡水市建设局网站,西安seo哪家好,专门做汽车配件保养的网站,那个网站做系统好【LeetCode】打卡–Python3算法18. 四数之和 题目 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a b c d 的值与 target 相等?找出所有满足条件且不重复…
衡水市建设局网站,西安seo哪家好,专门做汽车配件保养的网站,那个网站做系统好【LeetCode】打卡–Python3算法18. 四数之和
题目 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a b c d 的值与 target 相等?找出所有满足条件且不重复…
【LeetCode】打卡–Python3算法18. 四数之和
题目
给定一个包含 n 个整数的数组 nums
和一个目标值 target
,判断 nums
中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target
相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。满足要求的四元组集合为: [[-1, 0, 0, 1],[-2, -1, 1, 2],[-2, 0, 0, 2] ]
结果
执行用时 : 1604 ms, 在4Sum的Python3提交中击败了32.40% 的用户
内存消耗 : 13.1 MB, 在4Sum的Python3提交中击败了76.65% 的用户
Python解答
这题目就是三数之和再加了一层循环,因此直接在三数之和代码上外加了一层循环即可
class Solution:def fourSum(self, nums: List[int], target: int) -> List[List[int]]:data = set()nums.sort()for j in range(len(nums)-3):if(nums[j]>=0 and nums[j]>target):breakif(j>=1 and nums[j]==nums[j-1]):continuefor i in range(j+1,len(nums)-2):m = i + 1n = len(nums) - 1while(m < n):total = nums[m] + nums[n] + nums[i] + nums[j] - targetif(total==0):data.add((nums[j],nums[i],nums[m],nums[n]))m = m + 1n = n - 1elif(total > 0):while(nums[n-1]==nums[n] and n-1 > m):n = n - 1n = n - 1else:while(nums[m+1]==nums[m] and m+1 < n):m = m + 1m = m + 1return list(data)
我们下次再见,如果还有下次的话!!!
欢迎关注微信公众号:516数据工作室