leetcode18 四數之和

2021-09-26 03:49:11 字數 2082 閱讀 3580

題目:

給定乙個包含 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]

]

思路:

與三數之和的思路類似,多一層迴圈而已。先固定兩個數,再用雙指標找其餘兩個數

**:

class

solution

(object):

deffoursum

(self, nums, target)

:"""

:type nums: list[int]

:type target: int

:rtype: list[list[int]]

"""aim =

nums =

sorted

(nums)

for one in

range

(len

(nums)-3

):if one >

0and nums[one]

== nums[one-1]

:continue

two = one +

1while two <=

len(nums)-3

:if two > one +

1and nums[two]

== nums[two-1]

: two +=

1continue

left = two +

1 right =

len(nums)-1

while left < right:

sum= nums[one]

+ nums[two]

+ nums[left]

+ nums[right]

ifsum

== target:

[nums[one]

, nums[two]

, nums[left]

, nums[right]])

left +=

1 right -=

1while left < right and nums[left]

== nums[left-1]

: left +=

1while left < right and nums[right]

== nums[right+1]

: right -=

1elif

sum< target:

left +=

1while left < right and nums[left]

== nums[left -1]

: left +=

1else

: right -=

1while left < right and nums[right]

== nums[right +1]

: right -=

1 two +=

1return aim

LeetCode 18 四數之和

給定乙個包含 n 個整數的陣列 nums 和乙個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d 使得 a b c d 的值與 target 相等?找出所有滿足條件且不重複的四元組。注意 答案中不可以包含重複的四元組。示例 給定陣列 nums 1,0,1,0,2,2 和 ...

LeetCode 18 四數之和

給定乙個包含 n 個整數的陣列nums和乙個目標值target,判斷nums中是否存在四個元素 a,b,c 和 d 使得 a b c d 的值與target相等?找出所有滿足條件且不重複的四元組。注意 答案中不可以包含重複的四元組。示例 給定陣列 nums 1,0,1,0,2,2 和 target ...

leetcode18 四數之和

def foursum nums,target numlen,res,d len nums set if numlen 4 return nums.sort 二層迴圈遍歷任意兩個元素對和存放到字典d裡並把序號存起來 for p in range numlen for q in range p 1,n...