From 305ef69d5878ecaf1b9655e7899d663290f53af5 Mon Sep 17 00:00:00 2001 From: weiting-cn <2254912@qq.com> Date: Fri, 11 Feb 2022 16:09:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=EF=BC=9A0015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=EF=BC=8C0018.=E5=9B=9B=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=EF=BC=88=E5=8E=BB=E9=87=8D=E4=BC=98=E5=8C=96?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 4 ++++ problems/0018.四数之和.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index e191eabc..9b59e66d 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -138,8 +138,12 @@ public: */ if (nums[i] + nums[left] + nums[right] > 0) { right--; + // 当前元素不合适了,可以去重 + while (left < right && nums[right] == nums[right + 1]) right--; } else if (nums[i] + nums[left] + nums[right] < 0) { left++; + // 不合适,去重 + while (left < right && nums[left] == nums[left - 1]) left++; } else { result.push_back(vector{nums[i], nums[left], nums[right]}); // 去重逻辑应该放在找到一个三元组之后 diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index bad258c1..c6c55d50 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -91,9 +91,13 @@ public: // nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出 if (nums[k] + nums[i] > target - (nums[left] + nums[right])) { right--; + // 当前元素不合适了,可以去重 + while (left < right && nums[right] == nums[right + 1]) right--; // nums[k] + nums[i] + nums[left] + nums[right] < target 会溢出 } else if (nums[k] + nums[i] < target - (nums[left] + nums[right])) { left++; + // 不合适,去重 + while (left < right && nums[left] == nums[left - 1]) left++; } else { result.push_back(vector{nums[k], nums[i], nums[left], nums[right]}); // 去重逻辑应该放在找到一个四元组之后