文章目錄
- 題目<三數之和>--Python解法
- 題解
題目<三數之和>–Python解法
給你一個整數數組 nums ,判斷是否存在三元組 [nums[i], nums[j], nums[k]] 滿足 i != j、i != k 且 j != k ,同時還滿足 nums[i] + nums[j] + nums[k] == 0 。請你返回所有和為 0 且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例 1:
輸入:nums = [-1,0,1,2,-1,-4]
輸出:[[-1,-1,2],[-1,0,1]]
解釋:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元組是 [-1,0,1] 和 [-1,-1,2] 。
注意,輸出的順序和三元組的順序并不重要。
示例 2:
輸入:nums = [0,1,1]
輸出:[]
解釋:唯一可能的三元組和不為 0 。
示例 3:
輸入:nums = [0,0,0]
輸出:[[0,0,0]]
解釋:唯一可能的三元組和為 0 。
題解
該題與 兩數之和 相似。
采用雙指針解法:
class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""nums.sort() # 排序數組res = [] # 存儲結果m = len(nums) # 數組長度for i in range(m - 2): # 遍歷到倒數第三個元素if i > 0 and nums[i] == nums[i - 1]: # 跳過重復的 icontinuel = i + 1 # 左指針r = m - 1 # 右指針while l < r:total = nums[l] + nums[r]target = -nums[i] # 因為 nums[i] + nums[l] + nums[r] = 0if total == target:res.append([nums[i], nums[l], nums[r]])l += 1r -= 1# 跳過重復的 l 和 rwhile l < r and nums[l] == nums[l - 1]:l += 1while l < r and nums[r] == nums[r + 1]:r -= 1elif total < target: # 如果和太小,左指針右移l += 1else: # 如果和太大,右指針左移r -= 1return res
我認為該解法關鍵點在于,將第 i 個元素作為目標元素進行查找,這樣有了目標元素之后,就將三數之和轉換成的兩數之和。
然后比較需要注意的是一些邊界條件的處理以及避免重復得出相同列表的操作,首先是對目標元素的避免重復操作:
if i > 0 and nums[i] == nums[i-1]: #如果遇到重復相同的就下一個,避免得出的列表重復continue
然后就是對左指針以及右指針在遍歷數組元素中,相鄰元素的判斷,判斷是否重復,若重復就下一個元素:
while l < r and nums[l] == nums[l-1]: #如果指針在遍歷過程中,跳過重復的元素l += 1 #左指針右移while l < r and nums[r] == nums[r+1]:r -= 1 #右指針左移