博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
四数之和
阅读量:3981 次
发布时间:2019-05-24

本文共 712 字,大约阅读时间需要 2 分钟。

Q:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

分析:参考三数之和,将四数之和转换为三数之和即可,就是多加了一层循环

class Solution:    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:        nums.sort()        res= []        if len(nums)<4:            return res        for j in range(len(nums)):            if j>0 and nums[j]==nums[j-1]:                continue            # 转化为三数之和            sum1 = target - nums[j]            for i in range(j+1,len(nums)):                if i>j+1 and nums[i]==nums[i-1]:                    continue                # 转化为两数之和                sum2 = sum1 - nums[i]                l,r = i+1,len(nums)-1                while l

 

转载地址:http://gejui.baihongyu.com/

你可能感兴趣的文章
[LeetCode By Python]9. Palindrome Number
查看>>
[LeetCode By Python]13 Roman to Integer
查看>>
[leetCode By Python] 14. Longest Common Prefix
查看>>
[LeetCode By Python]107. Binary Tree Level Order Traversal II
查看>>
[LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
查看>>
[leetCode By Python]111. Minimum Depth of Binary Tree
查看>>
[LeetCode By Python]112. Path Sum
查看>>
[LeetCode By Python]118. Pascal's Triangle
查看>>
[LeetCode By Python]119. Pascal's Triangle II
查看>>
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>
[LeetCode By Python]125. Valid Palindrome
查看>>
[LeetCode By Python]136. Single Number
查看>>
[LeetCode BY Python]155. Min Stack
查看>>
[LeetCode By Python]167. Two Sum II - Input array is sorted
查看>>
[LeetCode By Python]168. Excel Sheet Column Title
查看>>
[LeetCode BY Python]169. Majority Element
查看>>
[LeetCode By Python]171. Excel Sheet Column Number
查看>>
[LeetCode By Python]172. Factorial Trailing Zeroes
查看>>
[LeetCode By MYSQL] Combine Two Tables
查看>>