StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/4sum/description/

# 题目大意

给出一个包含n个整数的数组nums以及一个目标值target, 这个数组是否存在有元素a,b,c,d使得a + b + c + d = target, 找出所有满足条件的a,b,c,d的组合

  • Example
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

# 题解

这题其实是第15题的变种, 相信看了这篇题解举一反三很容易能拿下这题, LeetCode:15.3Sum题解, Click Here!

这道题由于是求4个数的目标值, 所以需要滚动查询的数字由15题的两个变成了3个, 很暴力的一个方法, 在原来的循环上再加一层循环, 内部继续再剩余数组上枚举两个数求和即可

Hint:

如何优雅的避免重复也是一个坑, 外层两个循环都需要判断下当前选取的数字和上一次是不是相同的, 相同的直接跳过, 内层俩数字枚举时2也注意判断即可(千万别忘了某一层少写了这个条件, 不然美滋滋~)

# 复杂度

时间复杂度 O(n^3)

空间复杂度 O(1)

# AC代码

c++版本

class Solution
{
  public:
    vector<vector<int>> fourSum(vector<int> &nums, int target)
    {
        vector<vector<int>> ans;
        std::sort(nums.begin(), nums.end());
        const int len = nums.size();
        for (int i = 0; i < len - 3; ++i)
        {
            if (target > 0 && nums[i] > target)
            {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }
            for (int j = i + 1; j < len - 2; ++j)
            {
                if (target > 0 && nums[i] + nums[j] > target)
                {
                    break;
                }
                if (j > i + 1 && nums[j] == nums[j - 1])
                {
                    continue;
                }
                int midIndex = j + 1;
                int lastIndex = len - 1;
                while (midIndex < lastIndex)
                {
                    int curSum = nums[i] + nums[j] + nums[midIndex] + nums[lastIndex];
                    if (curSum == target)
                    {
                        ans.push_back({nums[i], nums[j], nums[midIndex++], nums[lastIndex--]});
                        while (midIndex < lastIndex && nums[midIndex] == nums[midIndex - 1])
                        {
                            ++midIndex;
                        }
                        while (midIndex < lastIndex && nums[lastIndex] == nums[lastIndex + 1])
                        {
                            --lastIndex;
                        }
                    }
                    else if (curSum > target)
                    {
                        --lastIndex;
                    }
                    else
                    {
                        ++midIndex;
                    }
                }
            }
        }
        return ans;
    }
};

go版本

func fourSum(nums []int, target int) [][]int {
	var ans [][]int
	lens := len(nums)
	sort.Sort(sort.IntSlice(nums))
	for i := 0; i < lens-3; i++ {
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}
		for j := i + 1; j < lens-2; j++ {
			if j > i+1 && nums[j] == nums[j-1] {
				continue
			}
			midIndex, lastIndex := j+1, lens-1
			for midIndex < lastIndex {
				curSum := nums[i] + nums[j] + nums[midIndex] + nums[lastIndex]
				if curSum == target {
					ans = append(ans, []int{nums[i], nums[j], nums[midIndex], nums[lastIndex]})
					midIndex++
					for midIndex < lastIndex && nums[midIndex] == nums[midIndex-1] {
						midIndex++
					}
					lastIndex--
					for midIndex < lastIndex && nums[lastIndex] == nums[lastIndex+1] {
						lastIndex--
					}
				} else if curSum > target {
					lastIndex--
				} else {
					midIndex++
				}
			}
		}
	}
	return ans
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

2 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读使用 + / − 按钮缩放 · 放大视图后可拖动 · 点击节点阅读单指拖动平移 · 使用 + / − 按钮缩放 · 点击节点阅读

当前文章引用本文本文引用
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用1

  • LeetCode_15: 3Sum
    AI 摘要

    文章讲解 LeetCode 三数之和问题:在整数数组中找出所有和为 0 且不重复的三元组。核心解法是先排序数组,固定第一个数,再用左右双指针在剩余区间夹逼寻找后两个数;根据三数之和与 0 的大小移动指针,并跳过重复元素避免重复结果。若首数大于 0 可提前结束。时间复杂度 O(n^2),空间复杂度 O(1),并给出 C++ 与 Go 实现。

文章关联