Golang | Leetcode Golang题解之第15题三数之和

题目:

题解:

Go 复制代码
func threeSum(nums []int) [][]int {
    n := len(nums)
    sort.Ints(nums)
    ans := make([][]int, 0)
 
    // 枚举 a
    for first := 0; first < n; first++ {
        // 需要和上一次枚举的数不相同
        if first > 0 && nums[first] == nums[first - 1] {
            continue
        }
        // c 对应的指针初始指向数组的最右端
        third := n - 1
        target := -1 * nums[first]
        // 枚举 b
        for second := first + 1; second < n; second++ {
            // 需要和上一次枚举的数不相同
            if second > first + 1 && nums[second] == nums[second - 1] {
                continue
            }
            // 需要保证 b 的指针在 c 的指针的左侧
            for second < third && nums[second] + nums[third] > target {
                third--
            }
            // 如果指针重合,随着 b 后续的增加
            // 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
            if second == third {
                break
            }
            if nums[second] + nums[third] == target {
                ans = append(ans, []int{nums[first], nums[second], nums[third]})
            }
        }
    }
    return ans
}
相关推荐
ZHE|张恒4 小时前
LeetCode - 寻找两个正序数组的中位数
算法·leetcode
努力学算法的蒟蒻5 小时前
day03(11.1)——leetcode面试经典150
java·算法·leetcode
im_AMBER6 小时前
Leetcode 43
笔记·学习·算法·leetcode
mifengxing7 小时前
力扣每日一题——接雨水
c语言·数据结构·算法·leetcode·动态规划·
数据知道8 小时前
Go语言设计模式:工厂模式详解
开发语言·设计模式·golang·go语言·工厂模式
小南家的青蛙9 小时前
LeetCode LCR 085 括号生成
算法·leetcode·职场和发展
晨非辰9 小时前
《数据结构风云》递归算法:二叉树遍历的精髓实现
c语言·数据结构·c++·人工智能·算法·leetcode·面试
Dream it possible!9 小时前
LeetCode 面试经典 150_链表_LRU 缓存(66_146_C++_中等)(哈希表 + 双向链表)
c++·leetcode·链表·面试