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
}
相关推荐
CoderYanger1 天前
贪心算法:1.柠檬水找零
java·算法·leetcode·贪心算法·1024程序员节
古城小栈1 天前
Go 语言 WebAssembly 原生支持:前后端一体化开发详解
开发语言·golang·wasm
2401_841495641 天前
【LeetCode刷题】跳跃游戏
数据结构·python·算法·leetcode·游戏·贪心算法·数组
CoderYanger1 天前
贪心算法:4.摆动序列
java·算法·leetcode·贪心算法·1024程序员节
天赐学c语言1 天前
12.13 - 岛屿数量 && C语言中extern关键字的作用
c++·算法·leetcode
_w_z_j_1 天前
全排列问题(包含重复数字与不可包含重复数字)
数据结构·算法·leetcode
古城小栈1 天前
Go语言调试:Delve+VS Code实战指南
golang
CoderYanger1 天前
A.每日一题——3606. 优惠券校验器
java·开发语言·数据结构·算法·leetcode
CoderYanger1 天前
D.二分查找-基础——744. 寻找比目标字母大的最小字母
java·开发语言·数据结构·算法·leetcode·职场和发展
元亓亓亓1 天前
LeetCode热题100--347. 前 K 个高频元素--中等
数据结构·算法·leetcode