zoukankan      html  css  js  c++  java
  • 15. 3Sum

    https://leetcode.com/problems/3sum/#/description

    Given an array S of n integers, are there elements abc in S 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.

    For example, given array S = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]
    

    Sol:

    Sort the input number list first. Use a pointer to traverse the list one time. Then use two pointers to squeeze from both ends of the rest of the list. Time O(n^n), space O(1).

    Since the list is sorted, we will skip any identical value.

    For the outer "for" loop, we continue if the outer values are the same.

    For the inner "while" loop, we check if the three sum equals to the target, 0 in this problem. If three sum < target, advanve left pointer and skip same element values. If three sum > target, advance right pointer and skip same element values. If three sum = target, append the tuple to the final output list,  advance both left and right pointers and skip same element values.  

      

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            # sort first and then use two pointers to push upon the mid point in the inner circle
            # skip repeated numbers
            # Time O(n^2), Space O(1)
            
            result = []
            if len(nums) < 3:
                return result
            
            nums.sort()
            target = 0
            
            # i is in the outer circle 
            for i in range(len(nums) - 1):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                    
                # initialize two pointer of inner cycles.
                # j is left pointer, k is right pointer. 
                j = i + 1
                k = len(nums) - 1
                while j < k:
                    if nums[i] + nums[j] + nums[k] < target:
                        j += 1
                        # skip identical value of left pointer.
                        while nums[j] == nums[j-1] and j < k:
                            j += 1
                    elif nums[i] + nums[j] +nums[k] > target:
                        k -= 1
                        # skip identical value of right pointer.
                        while nums[k] == nums[k+1] and j < k:
                            k -= 1
                    else:
                        result.append([nums[i], nums[j], nums[k]])
                        # after append the desired result, advance left and right pointer.
                        j += 1
                        k -= 1
                        # and skip identical values of left and right pointers.
                        while nums[j] == nums[j-1] and j < k:
                            j += 1
                        while nums[k] == nums[k+1] and j < k:
                            k -= 1
            return result
                        
                        
                    

    Note:

    1 Sort list in python:

     

    nums = [33,44,11,22,33]

    nums.sort()

    print nums

    ==>

    [11,22,33,33,44]

  • 相关阅读:
    Python Virtualenv 虚拟环境
    二叉树的左视图和右视图
    Vxlan简介
    2、程序的基本结构
    chef cookbook 实战
    eclipse 搭建ruby环境
    linux 安装软件出现/tmp 磁盘不足时 解决方案
    Python 可变对象与不可变对象
    Chapter 4-5
    Chapter 3
  • 原文地址:https://www.cnblogs.com/prmlab/p/7113555.html
Copyright © 2011-2022 走看看