From 7118f36b66e1def134fda97e992affbd0c5cd79b Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:38:05 -0500 Subject: [PATCH] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 49 ++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index eea3ba7a..1af8787b 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -151,7 +151,7 @@ public int[] twoSum(int[] nums, int target) { ``` Python: - +(版本一) 使用字典 ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -163,6 +163,53 @@ class Solution: records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key return [] ``` +(版本二)使用集合 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + #创建一个集合来存储我们目前看到的数字 + seen = set() + for i, num in enumerate(nums): + complement = target - num + if complement in seen: + return [nums.index(complement), i] + seen.add(num) +``` +(版本三)使用双指针 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + # 对输入列表进行排序 + nums_sorted = sorted(nums) + + # 使用双指针 + left = 0 + right = len(nums_sorted) - 1 + while left < right: + current_sum = nums_sorted[left] + nums_sorted[right] + if current_sum == target: + # 如果和等于目标数,则返回两个数的下标 + left_index = nums.index(nums_sorted[left]) + right_index = nums.index(nums_sorted[right]) + if left_index == right_index: + right_index = nums[left_index+1:].index(nums_sorted[right]) + left_index + 1 + return [left_index, right_index] + elif current_sum < target: + # 如果总和小于目标,则将左侧指针向右移动 + left += 1 + else: + # 如果总和大于目标值,则将右指针向左移动 + right -= 1 +``` +(版本四)暴力法 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i+1, len(nums)): + if nums[i] + nums[j] == target: + return [i,j] +``` Go: