三数之和【双指针】

Problem: 15. 三数之和

文章目录

  • 思路 & 解题方法
  • 复杂度
  • Code

思路 & 解题方法

两数相加的加强版,先确定第一个数,然后从右边去用双指针找另外两个数。注意题目需要避免重复的答案,所以要注意处理这个问题。

复杂度

时间复杂度:

添加时间复杂度, 示例: O ( n 2 ) O(n^2) O(n2)

空间复杂度:

添加空间复杂度, 示例: O ( n ) O(n) O(n)

Code

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

你可能感兴趣的:(研一开始刷LeetCode,双指针)