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行)

  • 相关阅读:
    with admin option 和 with grant option 的区别 (转)
    压缩数据块
    建表时pctfree和pctused参数作用
    Oracle哪些错误会写进alert日志
    Oracle 差异、增量、零级备份
    模拟原生的promise
    react-loadable 实现组件按需加载
    react 中配置 http-proxy-middleware
    craco 配置 less.module
    ESLint: 'React' was used before it was defined.(no-use-before-define)
  • 原文地址:https://www.cnblogs.com/plank/p/9159421.html
Copyright © 2011-2022 走看看