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
}
相关推荐
名字还没想好☜1 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
alphaTao2 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
ttwuai3 小时前
GoFrame 后台日志清空失败:无 WHERE 删除为什么被拦住
前端·golang
进击的程序猿~4 小时前
Go 并发底层原理面试学习指南
开发语言·面试·golang
Hi李耶9 小时前
【LeetCode】9-回文数
算法·leetcode·职场和发展
geovindu11 小时前
go:loghelper
开发语言·后端·golang
海绵天哥12 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
会编程的土豆13 小时前
GoWeb 处理请求详解:请求行、请求头、请求参数与给客户端响应
开发语言·http·golang
tkevinjd1 天前
力扣131-分割回文串
算法·leetcode·深度优先
zander2581 天前
LeetCode 78. 子集
算法·leetcode·深度优先