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

    题目:

    Given an array nums of n integers, are there elements abc 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]
    ]

    思路:

    因为给的数据中可能有重复元素,想到将数组排序,以方便跳过重复元素。基于排序的元组,可以选定一个目标值,再用两端逼近的方式来求出和为目标值的两个元素。整个算法的时间复杂度为O(n^2)。

    解题代码如下:

     1 class Solution(object):
     2     def threeSum(self, nums):
     3         nums.sort()
     4         res = []
     5         for i in range(len(nums) - 2):
     6             if i == 0 or (i > 0 and nums[i] != nums[i - 1]):
     7                 target = 0 - nums[i]
     8                 lo, hi = i + 1, len(nums) - 1
     9                 while lo < hi:
    10                     if nums[lo] + nums[hi] == target:
    11                         res.append([nums[i], nums[lo], nums[hi]])
    12                         while lo < hi and nums[lo] == nums[lo + 1]:
    13                             lo += 1
    14                         while lo < hi and nums[hi] == nums[hi - 1]:
    15                             hi -= 1
    16                         lo, hi = lo + 1, hi - 1
    17                     elif nums[lo] + nums[hi] > target:
    18                         hi -= 1
    19                     else:
    20                         lo += 1
    21         return res

    为避免结果中出现冗余值,有两点需要注意:

    一个是外层遍历选取target值是,应保证当前元素和之前一个元素不相等(见第6行)

    一个是内层循环中找到一组符合条件的值后,应调整两个指针的位置,跳开重复元素(见第12、13行)

  • 相关阅读:
    EditPlus v2.12 使用技巧集萃
    GridView列数字、货币和日期的显示格式
    使用模态窗口编辑数据
    求sql查询语句(转换数据表由纵向转换成横向)
    插入数据 存储过程生成帐单号
    65个源代码网站
    C#抓屏(截屏)
    SQL中SET NOCOUNT的用法
    在Visual Studio2005 中调试JavaScript
    WinForm下App.config配置文件的读与写
  • 原文地址:https://www.cnblogs.com/plank/p/9159421.html
Copyright © 2011-2022 走看看