From a20a9b7086a64311d6635edbd1537859ecf556d7 Mon Sep 17 00:00:00 2001 From: supertitman2023 <1041703814@qq.com> Date: Sat, 4 Nov 2023 03:37:45 +0000 Subject: [PATCH] =?UTF-8?q?update=20solution/0000-0099/0001.Two=20Sum/READ?= =?UTF-8?q?ME.md.=20=E6=9B=B4=E6=96=B0=E4=B8=A4=E4=B8=AAc++=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=B0=8F=E9=97=AE=E9=A2=98=EF=BC=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.原来的代码确实存在问题,它会导致无限循环。因为在 for (int i = 0;; ++i) 的循环中,我们没有设置循环条件,所以这个循环将无限执行下去,直到出现错误。 为了修复这个问题,我们应该设置一个适当的循环条件。可以使用 for (int i = 0; i < nums.size(); ++i),这样循环将在遍历完 nums 中的所有元素后终止。 2.在 C++ 的 unordered_map 容器中,可以使用 find() 函数来判断某个键是否存在于容器中。相比于 count() 函数,find() 函数在判断存在性时更为高效。 .与 count() 函数返回键出现的次数不同,find() 函数返回一个指向匹配键的迭代器。如果找到了匹配的键,则返回指向该键的迭代器;如果没有找到匹配的键,则返回指向容器末尾的迭代器。通过检查 find() 函数返回的迭代器是否等于容器的末尾迭代器,我们可以判断键是否存在于容器中。如果迭代器等于容器的末尾迭代器,则表示没有找到匹配的键,否则表示找到了匹配的键。 Signed-off-by: supertitman2023 <1041703814@qq.com> --- solution/0000-0099/0001.Two Sum/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solution/0000-0099/0001.Two Sum/README.md b/solution/0000-0099/0001.Two Sum/README.md index 8cb31ebef6..ac2fdaf748 100644 --- a/solution/0000-0099/0001.Two Sum/README.md +++ b/solution/0000-0099/0001.Two Sum/README.md @@ -107,10 +107,10 @@ class Solution { public: vector twoSum(vector& nums, int target) { unordered_map m; - for (int i = 0;; ++i) { + for (int i = 0; i < nums.size(); ++i) { int x = nums[i]; int y = target - x; - if (m.count(y)) { + if (m.find(y) != m.end()) { return {m[y], i}; } m[x] = i; -- Gitee