提交 27511768 编写于 作者: jhaos's avatar jhaos

Add new file

上级 93a763d6
给定一个整数数组 `nums` 和一个目标值 `target`,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
**示例:**
```
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
```
通过次数`1,430,402` 提交次数`2,888,040`
**代码实现:**
1. 暴力求解
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
re = []
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j]==target:
re.append(i)
re.append(j)
return re
```
2. 排序+双指针
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
temp=nums.copy()
temp.sort()
i=0
j=len(nums)-1
while i<j:
if (temp[i]+temp[j])>target:
j=j-1
elif (temp[i]+temp[j])<target:
i=i+1
else:
break
p=nums.index(temp[i])
nums.pop(p)
k=nums.index(temp[j])
if k>=p:
k=k+1
return [p,k]
```
3. Hash
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash={}
for i in range(len(nums)):
if hash.get(target-nums[i]) is not None :
return [hash.get(target-nums[i]),i]
hash[nums[i]]=i
```
```
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册