leetcode刷题笔记(Golang)--15. 3Sum

原题链接15. 3Sum
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]
]
解题思路:转化为n个2sum问题

func threeSum(nums []int) [][]int {
    var res [][]int
    sort.Ints(nums)
    lg := len(nums)
    for i := 0; i < lg-2; i++ {
        l := i + 1
        r := lg - 1
        if i > 0 && nums[i] == nums[i-1] {
            continue
        }
        for l < r {
            if nums[i]+nums[l]+nums[r] == 0 {
                res = append(res, []int{nums[i], nums[l], nums[r]})
                l++
                r--
                for l < r && nums[l] == nums[l-1] {
                    l++
                }
                for l < r && nums[r] == nums[r+1] {
                    r--
                }
            } else if nums[i]+nums[l]+nums[r] < 0 {
                l++
            } else {
                r--
            }
        }
    }
    return res
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,505评论 0 13
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,725评论 0 3
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,936评论 0 0
  • 一个夏日的傍晚。我和妈妈手拉着手,一起走在郊外,郊外的一边是花池。另一边是广场。我看到广场那一边非常热闹。而花池里...
    真善美521阅读 173评论 0 1
  • 哪怕是变成甄太太,也依稀能看到过去记忆里的她,少女情怀的味道。她在甄家的大院里笑盈盈地给我们这几个客人张罗点心,清...
    林大侠阅读 369评论 0 0