mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0001.两数之和.md
This commit is contained in:
@ -151,7 +151,7 @@ public int[] twoSum(int[] nums, int target) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
(版本一) 使用字典
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||||
@ -163,6 +163,53 @@ class Solution:
|
|||||||
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
|
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
return []
|
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:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user