LeetCode2——三數之和

在這裏插入圖片描述
在這裏插入圖片描述

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        res = []

        # 如果nums爲空或者nums的長度小於3,返回空列表
        if(not nums or n<3):
            return []

        # 對nums進行排序,以便有效的利用順序的性質
        nums.sort()

        for i in range(n):
            if nums[i] > 0: # 如果nums[i] > 0 說明往後就找不到了,因爲這是一個有序的列表,此時我們需要返回res
                return res
            if i > 0 and nums[i]==nums[i-1]:  # 如果有重複元素,跳過。因爲我們已經用該元素遍歷過列表了,在遍歷一次會重複
                continue
            
            # 定義左、右指針
            L = i+1
            R = n-1
            while(L<R):
                if(nums[i]+nums[L]+nums[R] == 0):
                    res.append([nums[i],nums[L],nums[R]])
                    while(L<R and nums[L] == nums[L+1]):  # 因爲我們固定了nums[i],所以這裏L指針只能是沒有重複的。
                        L = L+1
                    while(L<R and nums[R] == nums[R-1]):
                        R = R-1
                    L = L+1 # 如果進入了上面的while循環,則L總共會加2
                    R = R-1
                elif nums[i]+nums[L]+nums[R] > 0:
                    R = R-1
                else:
                    L = L+1
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章