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]

  • 相关阅读:
    《objective-c基础教程》学习笔记(三)—— 从结构体到面向对象
    《objective-c基础教程》学习笔记(二)—— for循环的基本应用
    《objective-c基础教程》学习笔记 (一)—— 开发环境配置和简单类型输出
    asp.net mvc 3.0 知识点整理 ----- (4).asp.net mvc 3 和asp.net mvc 4 对比
    git简单使用(上篇)
    git简单使用(下篇)
    Spring核心概念之Ioc
    "注解"的用法
    struts2进阶篇(3)
    struts2进阶篇(2)
  • 原文地址:https://www.cnblogs.com/prmlab/p/7113555.html
Copyright © 2011-2022 走看看