From ae2e89b9d4397b485a7e546cdb0aa6526b7e1446 Mon Sep 17 00:00:00 2001 From: Senrian <47714364+Senrian@users.noreply.github.com> Date: Sat, 21 Mar 2026 00:35:19 +0800 Subject: [PATCH 1/2] fix: Use HashMap O(n) approach for C/Java/Python (fixes issue #134) --- 0001-Two-Sum/Article/0001-Two-Sum.md | 79 ++++++++++++---------------- 1 file changed, 33 insertions(+), 46 deletions(-) diff --git a/0001-Two-Sum/Article/0001-Two-Sum.md b/0001-Two-Sum/Article/0001-Two-Sum.md index 95e8591c..27a549e4 100644 --- a/0001-Two-Sum/Article/0001-Two-Sum.md +++ b/0001-Two-Sum/Article/0001-Two-Sum.md @@ -3,7 +3,6 @@ > 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ]() 系列文章之一。 > > 同步博客:https://www.algomooc.com -> 题目来源于 LeetCode 上第 1 号问题:两数之和。题目难度为 Easy,目前通过率为 45.8% 。 @@ -72,27 +71,27 @@ public: * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ - int *ans=(int *)malloc(2 * sizeof(int)); - int i,j; - bool flag=false; - for(i=0;i record = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + if (record.containsKey(complement)) { + return new int[] { i, record.get(complement) }; } + record.put(nums[i], i); } - - return ans; - + return new int[] {}; } } ``` @@ -132,17 +123,13 @@ class Solution { # 空间复杂度:O(n) class Solution(object): def twoSum(self, nums, target): - l = len(nums) - print(nums) - ans=[] - for i in range(l-1): - for j in range(i+1,l): - if nums[i]+nums[j] == target: - ans.append(i) - ans.append(j) - print([i,j]) - break - return ans + record = {} + for i, num in enumerate(nums): + complement = target - num + if complement in record: + return [i, record[complement]] + record[num] = i + return [] ``` ![](../../Pictures/qrcode.jpg) From 5fd7900cbdff2c3b227bccc580a840caa8ca749a Mon Sep 17 00:00:00 2001 From: Senrian <47714364+Senrian@users.noreply.github.com> Date: Sat, 21 Mar 2026 00:42:00 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Fix=20#134:=20Replace=20O(n=C2=B2)=20brute?= =?UTF-8?q?=20force=20with=20O(n)=20hash=20map=20in=20C/Java/Python=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit