lc15. 3Sum

169 阅读1分钟
  1. 3Sum Medium

3929

443

Favorite

Share 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.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]

思路:

  1. 两次循环加双指针,时间复杂度O(n^2)

代码:python3

1.class Solution:
   
class Solution:
    def threeSum(self, nums):
        nums.sort()
        i, N, result = 0, len(nums), []
        while i < N - 2:
            j, k = i + 1, N - 1
            while j < k:
                Sum = nums[i] + nums[j] + nums[k]
                if not Sum:
                    result.append([nums[i], nums[j], nums[k]])
                    while j < k and nums[j] == nums[j + 1]: j += 1
                    j += 1
                    while j < k and nums[k] == nums[k - 1]: k -= 1
                    k -= 1
                elif Sum < 0:
                    while j < k and nums[j] == nums[j + 1]: j += 1
                    j += 1
                else:
                    while j < k and nums[k] == nums[k - 1]: k -= 1
                    k -= 1
            while i < N - 2 and nums[i] == nums[i + 1]: i += 1
            i += 1
        return result