leetcode 每日一题 15. 三数之和

双指针法

思路:

首先对原数组进行排序,然后从头开始遍历,当遇到nums[i]>0时终止。在遍历过程中,对遍历元素i后面剩余子数组首尾添加指针L和R,通过移动LR找到满足题设条件的[i,L,R]。这里要注意的是,为了避免重复的情况,在遍历过程中,如果遍历的元素nums[i]和它之前元素nums[i-1]相同,则略过此次操作,继续下一个。在找到满足条件的L,R时,如果nums[L+1]==nums[L],则L向右移动到不同的元素位置或者和R位置相同为止,同理如果nums[R-1]==nums[R],则R向左移动到不同的元素位置或者和L位置相同为止。

例如:

[-1,0,1,2,-1,-4]


代码:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        length = len(nums)
        if length < 3:
            return []
        result = []
        nums.sort()
        for i in range(length):
            if nums[i]>0:
                return result
            if i > 0 and nums[i] == nums[i-1]:
                continue
            L = i+1
            R = length-1
            while L<R:
                if nums[i]+nums[L]+nums[R] == 0:
                    result.append([nums[i],nums[L],nums[R]])
                    while L<R and nums[L+1]==nums[L]:
                        L += 1
                    while L<R and nums[R-1]==nums[R]:
                        R -= 1
                    L += 1
                    R -= 1
                elif nums[i]+nums[L]+nums[R] > 0:
                    R -= 1
                else:
                    L += 1
        return result

 

猜你喜欢

转载自www.cnblogs.com/nilhxzcode/p/12785803.html
今日推荐