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
}
相关推荐
__AtYou__37 分钟前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
转调1 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
千年死缓2 小时前
go+redis基于tcp实现聊天室
redis·tcp/ip·golang
huanxiangcoco2 小时前
152. 乘积最大子数组
python·leetcode
希望有朝一日能如愿以偿4 小时前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato4 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
数据分析螺丝钉5 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
￴ㅤ￴￴ㅤ9527超级帅5 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
吃着火锅x唱着歌6 小时前
Redis设计与实现 学习笔记 第五章 跳跃表
golang
鱼跃鹰飞6 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试