Files
Simple_Drawing/file_keep/chart/file/2120470592021825
T
2021-09-22 12:49:06 +08:00

71 lines
2.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 力扣
## 简单
### 两数之和
> 给定一个整数数组 `nums` 和一个整数目标值 `target`,请你在该数组中找出 和为目标值 `target` 的那 两个 整数,并返回它们的数组下标。
>
> 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
```shell
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
```
**题解**
双指针解法
> 标准的双指针写法 利用两层循环来暴力全部试过 `3004 ms` `15.3 MB`
```python
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
```
> 本质依旧是双指针法 只不过用in方法代替了一次循环 而且 直接寻找目标而不是全部试一次 `408 ms` `15.3 MB ` 同时可以看出 `in` 方法是很高效的
```python
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
num = nums.pop(0)
if target - num in nums:
return [i, nums.index(target - num)+i+1]
```
哈希解法
> 首先我们循环一遍数组 来检查与目标只差在没在哈希表里 如果在就说明是我们的目标元素 因为只循环了一遍所以 不存在重复的问题
```python
# 很标准的写法 也不知道为什么会有那么多其他的写法
# 20 ms 15.8 MB
class Solution(object):
def twoSum(self, nums, target):
dct={} # 用于存放数据 以数组里的元素为键索引为值
for i,n in enumerate(nums):
a=target-n # 如果是的话另一个元素应该是什么
# 如果这里用get方法 时间会变成 32 ms 15.7 MB
if a in dct: # 查看是否在哈希里
return [dct[a],i] # 如果在直接返回就可以了
else:
dct[n]=i
```