LeetCode T18
class Solution:
def fourSum(self, nums, target):
d=dict()
n = len(nums)
if n<4:
return []
if n == 4:
if sum(nums)==target:
return [nums]
# 遍歷一次,計算兩個數的和,存在字典裡,鍵是兩數之和
# 值是一個列表,儲存所有符合條件的兩數索引的列表
# 如 [1,2,3,4,1] 算兩數和為5,則有:5:[[0,3],[1,2],[3,4]]
for i in range(n):
for j in range(i+1,n):
if nums[i]+nums[j] not in d.keys():
d[nums[i]+nums[j]] = [[i,j]]
else:
d[nums[i]+nums[j]].append([i,j])
# 結果列表
result= []
for i in range(n):
for j in range(i+1,n):
# 目標值減去兩數的差,在字典中能找到,但索引不重複(值可以相同,但在原陣列列表的位置不同)
for a,b in d.get(target-nums[i]-nums[j],[]):
# 索引集合
temp={i,j,a,b}
# 如果索引值都不重複
if len(temp)==4:
# 排序是為了方便判斷後序滿足條件的列表在不在結果列表裡
# 如果在,直接過濾掉
sumList = sorted([nums[t] for t in temp])
if sumList not in result:
result.append(sumList)
return result
相關文章
- 【LeetCode】如何學習LeetCode?LeetCode
- LeetcodeLeetCode
- LeetCode in actionLeetCode
- Leetcode AnagramsLeetCode
- Leetcode SortListLeetCode
- Leetcode ReorderListLeetCode
- leetcode SubsetsLeetCode
- Leetcode PermutationsLeetCode
- [LeetCode刷題筆記] 關於LeetCode的前言LeetCode筆記
- 我的 LeetCodeLeetCode
- Leetcode學習LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- LeetCode 克隆圖LeetCode
- Leetcode Perfect SquaresLeetCode
- Leetcode Sort ColorsLeetCode
- Leetcode Sort ArrayLeetCode
- 【LeetCode】Jewels and StonesLeetCode
- 嘗試 LeetcodeLeetCode
- LeetCode 消除遊戲LeetCode遊戲
- Leetcode03LeetCode
- Leetcode LRU CacheLeetCode
- Leetcode Path SumLeetCode
- LeetCode Min StackLeetCode
- Leetcode Word SearchLeetCode
- Leetcode Number of islandsLeetCode
- Leetcode-394LeetCode
- Leetcode 921 JavascriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- LeetCode:快速排序LeetCode排序
- [LeetCode] Group AnagramLeetCode
- leetcode690LeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 513 javascriptLeetCodeJavaScript
- Leetcode725LeetCode
- Leetcode目錄LeetCode