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
}
相关推荐
Navigator_Z10 小时前
LeetCode //C - 1328. Break a Palindrome
c语言·算法·leetcode
NendoZen10 小时前
Bubble Tea V2构建Go TUI应用教程
开发语言·golang·xcode
pan_junbiao11 小时前
Go 语言变量的声明与初始化
开发语言·javascript·golang
pan_junbiao18 小时前
Go 语言基本数据类型
java·前端·golang
codeejun1 天前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
利威尔xu1 天前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
Sakura_j_h_1 天前
TypeScript 7.0 换 Go 编译器后,我先在 6.0 清完默认值
javascript·golang·typescript·vite·前端工程化·tsc
旖旎夜光2 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
木井巳2 天前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
码途行者2 天前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang