題目:
給定一個包含 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]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/4sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
個人思路:
三指針法再加一層遍歷?毫無思路。加一個毫字可以充分體現我的悲痛與無奈。
官方答案推薦:
還真就固定兩點內部再用一個雙指針法。。。O(n^3)。。。跟三指針那個基本沒區別。
python代碼:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
result = []
if(len(nums) < 4):
return result
nums.sort()
for start in range(len(nums) - 3):
if start>0 and nums[start] == nums[start-1]:
continue
for end in range(len(nums)-1,start+2,-1):
if end< len(nums)-1 and nums[end] == nums[end +1]:
continue
left,right = start+1,end-1
while left < right:
curResult = nums[start] + nums[end] + nums[left] + nums[right]
if(curResult > target):
right -=1
elif curResult < target:
left +=1
else:
result.append([nums[start],nums[end],nums[left],nums[right]])
while left<right and nums[left] == nums[left+1]:
left +=1
while left<right and nums[right] == nums[right-1]:
right -=1
left +=1
right -=1
return result
反思:
想多了。。。還有寫代碼的時候沒有考慮到target<0的情況。