美文网首页
18. 4Sum 四数之和

18. 4Sum 四数之和

作者: sarto | 来源:发表于2022-03-25 21:19 被阅读0次

题目

给定一个数组 nums 和目标数 target。找到 四个数字使得这四个数相加等于目标数。

解析

和三数相加一样,先排序,固定两个数字,然后左右指针移动三个两个数字,去重方法也相同。

  1. 左右指针移动时,判断重复
  2. 移动固定指针时,步进到下一个不同的数字。

所以这是一个 n3 的时间复杂度。

伪代码

for i:=0; i< len-3; i++
    for j := i+1; j<len-2; j++
        h := j+1
        t := len-1
        for  h<t
          if sum == target
            if valid 
              rst=append(sum)
             h++,t--
          if sum < target
             h++
          if sum > target
             t--
      for nums[j]==nums[j+1]
          j++

    for nums[i] == nums[i+1]
        i++
    return rst

代码

func fourSum(nums []int, target int) [][]int {
    sort.Ints(nums)
    var rst [][]int
    for i:=0; i<len(nums)-3; i++ {
        for j:=i+1; j<len(nums)-2; j++ {
            h:=j+1
            t:=len(nums)-1
            for ; h<t; {
                sum := nums[i] + nums[j] + nums[h] + nums[t]
                if sum==target{
                    if h==j+1 || t==len(nums)-1 || nums[h] != nums[h-1] || nums[t] != nums[t+1] {
                        rst = append(rst, []int{nums[i], nums[j], nums[h], nums[t]})
                    } 
                    h++
                    t--
                }
                if sum < target {
                    h++
                }
                if sum > target {
                    t--
                }
            }
            for j<len(nums)-2 && nums[j] == nums[j+1] {
                j++
            }
        }
        for i < len(nums)-3 && nums[i] == nums[i+1] {
            i++
        }
    }
    return rst
}
image.png

后记

  1. 定点移动时,也要注意游标边界

相关文章

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • 18. 4Sum/四数之和

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum 四数之和

    题目 给定一个数组 nums 和目标数 target。找到 四个数字使得这四个数相加等于目标数。 解析 和三数相加...

  • LeetCode每日一题,四数之和

    题目 四数之和[https://leetcode-cn.com/problems/4sum/] https://l...

  • 【Leetcode算法题】18. 四数之和

    By Long Luo 18. 四数之和[https://leetcode-cn.com/problems/4su...

  • LeetCode-18 四数之和

    题目:18. 四数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第18题四数之和,这是一道中等题。像...

  • 18. 四数之和

    一、题目原型: 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四...

  • 18. 四数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

  • 18. 四数之和

    18.四数之和 给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素a,b,...

网友评论

      本文标题:18. 4Sum 四数之和

      本文链接:https://www.haomeiwen.com/subject/xygrjrtx.html