【LeetCode】18. 4Sum 解題報告(Python)
阿新 • • 發佈:2019-01-30
目錄
題目描述
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
題目大意
找出一個數組中所有的和為target的四個數字,要求返回的結果裡面不準有重複的四元組。
解題方法
遍歷
總結一下K-sum題目。
- 首先先排序
- 然後用K - 2個指標做O(N^(K - 2))的遍歷
- 剩下2個指標從第2步的剩餘區間裡面找,找的方式是使用兩個指標p, q分別指向剩餘區間的首尾,判斷兩個指標的和與target - 第2步的和的關係,對應的移動指標。即如果兩個數的和大了,那麼,q–;如果兩個數的和小了,那麼,p++;等於的話,輸出結果。要時刻注意p < q.
- 用p,q查詢剩餘區間結束之後,需要移動前面的K-2個值,這裡需要在移動的過程中做個去重,找到和前面不同的值繼續查詢剩餘區間。
時間複雜度是O(N^3),空間複雜度是O(1).
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
N = len(nums)
nums.sort( )
res = []
i = 0
while i < N - 3:
j = i + 1
while j < N - 2:
k = j + 1
l = N - 1
remain = target - nums[i] - nums[j]
while k < l:
if nums[k] + nums[l] > remain:
l -= 1
elif nums[k] + nums[l] < remain:
k += 1
else:
res.append([nums[i], nums[j], nums[k], nums[l]])
while k < l and nums[k] == nums[k + 1]:
k += 1
while k < l and nums[l] == nums[l - 1]:
l -= 1
k += 1
l -= 1
while j < N - 2 and nums[j] == nums[j + 1]:
j += 1
j += 1 # 重要
while i < N - 3 and nums[i] == nums[i + 1]:
i += 1
i += 1 # 重要
return res
相似題目
參考資料
日期
2018 年 10 月 30 日 —— 啊,十月過完了