From 4796c816421924edff6bdc2521ae0880e2d80f39 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:35:53 +0800 Subject: [PATCH] =?UTF-8?q?update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C=EF=BC=9A=E5=8A=A0=E6=B3=A8=E9=87=8A=EF=BC=8C=E7=BB=99?= =?UTF-8?q?java=E4=BB=A3=E7=A0=81=E4=B8=80=E7=82=B9=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 7bada9af..56cff527 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -134,12 +134,13 @@ public int[] twoSum(int[] nums, int target) { } Map map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ - int temp = target - nums[i]; + int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key if(map.containsKey(temp)){ res[1] = i; res[0] = map.get(temp); + break; } - map.put(nums[i], i); + map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中 } return res; } @@ -152,16 +153,17 @@ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: records = dict() - for index, value in enumerate(nums): - if target - value in records: + for index, value in enumerate(nums): + if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key return [records[target- value], index] - records[value] = index + records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key return [] ``` Go: ```go +// 暴力解法 func twoSum(nums []int, target int) []int { for k1, _ := range nums { for k2 := k1 + 1; k2 < len(nums); k2++ { @@ -216,11 +218,11 @@ Javascript ```javascript var twoSum = function (nums, target) { let hash = {}; - for (let i = 0; i < nums.length; i++) { + for (let i = 0; i < nums.length; i++) { // 遍历当前元素,并在map中寻找是否有匹配的key if (hash[target - nums[i]] !== undefined) { return [i, hash[target - nums[i]]]; } - hash[nums[i]] = i; + hash[nums[i]] = i; // 如果没找到匹配对,就把访问过的元素和下标加入到map中 } return []; };