This is a place to put my clutters, no matter you like it or not, welcome here.
0%
15. 3Sum
Posted onEdited onIn面試Views: Symbols count in article: 1.6kReading time ≈1 mins.
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Notice that the solution set must not contain duplicate triplets.
from typing import List class Solution(object): def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() # 小到大排序 added = set() out = [] for i in range(len(nums) - 1, -1, -1): last = nums[i] start, end = 0, i - 1 while start < end: s = last + nums[start] + nums[end] # 加總 if s == 0: if (last, nums[start], nums[end]) not in added: # 紀錄沒看過的合法組合 out.append([last, nums[start], nums[end]]) added.add((last, nums[start], nums[end])) start += 1 # 持續加到結束 elif s > 0: # 總和過多 end -= 1 else: start += 1 # 總和過少 return out