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 238LeetCode
- LeetCode 164 最大間距 HERODING的LeetCode之路LeetCode
- LeetCode 143 重排連結串列 HERODING的LeetCode之路LeetCode
- LeetCode問題LeetCode
- 【LeetCode】Jewels and StonesLeetCode
- Leetcode 513 javascriptLeetCodeJavaScript
- LeetCode 162 JavascriptLeetCodeJavaScript
- Leetcode 921 JavascriptLeetCodeJavaScript
- [Leetcode] Edit DistanceLeetCode
- LeetCode 克隆圖LeetCode
- LeetCode #378 JavaScriptLeetCodeJavaScript
- LeetCode 747 JavaScriptLeetCodeJavaScript
- Leetcode725LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- Leetcode03LeetCode
- LeetCode 799 JavaScriptLeetCodeJavaScript
- leetcode690LeetCode
- [LeetCode] Group AnagramLeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 229 JavaScriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- Leetcode目錄LeetCode
- LeetCode:快速排序LeetCode排序
- leetcode Sum系列LeetCode
- LeetCode三則LeetCode
- LeetCode2:LeetCode
- The best LeetCode NodesLeetCode
- LeetCode兩則LeetCode
- Leetcode學習LeetCode
- leetcode no.1LeetCode
- leetcode開篇LeetCode