Skip to content

Latest commit

 

History

History
87 lines (73 loc) · 2.67 KB

15.三数之和.md

File metadata and controls

87 lines (73 loc) · 2.67 KB

题目描述

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 示例 2:

输入:nums = [] 输出:[] 示例 3:

输入:nums = [0] 输出:[]

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/3sum

解题思路

这道题难点主要在于如何避免查出重复的三元组

用一个三指针, curIndex, left, right分别为当前查找的基数索引, left低位索引curIndex+1, right高位索引len(nums)-1

  • 起始特判: 长度小于3, 直接返回空数组
  • 数组排序,依次从小到大遍历curIndex
  • nums[curIndex]值大于0, 则必定不符合条件, 直接退出
  • curIndex如果和前一个curIndex值相同,那么是重复查找,直接跳过
  • curIndex确认之后,就是找-(nums[curIndex])的两数之和了
    • 找到之后,为了避免重复三元组,缩小left、right区间后判断是否和上一个数值相同,如果相同跳过继续收缩

代码如下

func threeSum(nums []int) [][]int {
    if len(nums) < 3 {
        return [][]int{}
    }

    sort.Ints(nums)

    result := [][]int{}
    for curIndex := 0; curIndex < len(nums)-2; curIndex++ {
        //当前最低位(最小值为正数 那么必定没有符合的三元组)
        if nums[curIndex] > 0 {
            break
        }
        //当前的基数 和前一个相同, 不需要重复求解了
        if curIndex > 0 && nums[curIndex] == nums[curIndex-1] {
            continue
        }
        left, right := curIndex+1, len(nums)-1
        for left < right {
            sum := nums[curIndex] + nums[left] + nums[right]
            if sum == 0 {
                result = append(result, []int{nums[curIndex], nums[left], nums[right]})
                left++
                for left < right && nums[left] == nums[left-1] { //去掉重复比较的数
                    left++
                }
                right--
                for right > left && nums[right] == nums[right+1] {
                    right--
                }
            } else if sum > 0 { //三数之和大于0  总和要缩小 right--
                right--
            } else {
                left++
            }
        }
    }

    return result
}

复杂度分析

时间复杂度:O(n^2) 遍历N-2个curIndex数组,每个curIndex需要再遍历一次找两数之和

空间复杂度: O(1)