Leetcode:两数之和
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
第一次提交:
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for x in nums :
for y in nums:
if x + y == target:
return [nums.index(x), nums.index(y)]
问题
重复用了数组中同样的元素
第二次提交:
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for x in nums :
for y in nums:
if x + y == target:
if x == y:
break
return [nums.index(x), nums.index(y)]
问题
遇到不同数组的相同元素无法运行
想到的解决办法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for x in nums :
for y in nums:
if x + y == target :
if (x == y) & (nums.index(x) == nums.index(y)):
continue
return [nums.index(x), nums.index(y)]
不可行,nums.index(x)只能找到靠前的元素的位置
还无法解决
大佬们的解题方法
1.用 Python 中 list 的相关函数求解:
方法一:
解题关键主要是想找到 num2 = target - num1,是否也在 list 中
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lens = len(nums)
j=-1
for i in range(lens):
if (target - nums[i]) in nums:
if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):
#如果num2=num1,且nums中只出现了一次,说明找到是num1本身
continue
else:
j = nums.index(target - nums[i],i+1)
#index(x,i+1)是从num1后的序列后找num2
#这样就不会有i=j的问题
break
if j>0:
return [i,j]
else:
return []
耗时1200ms
方法二:
解题思路是在方法一的基础上。num2 的查找并不需要每次从 nums 查找一遍,只需要从 num1 位置之前或之后查找即可,这可以很好的排除num1自身,不用判断num2=num1时是不是找到了num1自身,使取值不会重复。为了方便 index 这里选择从 num1 位置之前查找:
def twoSum(nums, target):
lens = len(nums)
j=-1
for i in range(1,lens):
temp = nums[:i]
if (target - nums[i]) in temp:
j = temp.index(target - nums[i])
break
if j>=0:
return [j,i]
耗时600ms
2.用字典模拟哈希求解
方法一:
这种办法相较于方法一其实就是字典记录了 num1 和 num2 的值和位置,而省了再查找 num2 索引的步骤。
def twoSum(nums, target):
hashmap={}
for ind,num in enumerate(nums):
hashmap[num] = ind
for i,num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and i!=j:
return [i,j]
耗时80ms
方法二:
类似 用list 的相关函数求解的方法二,不需要 mun2 不需要在整个 dict 中去查找。可以在 num1 之前的 dict 中查找,因此就只需要一次循环可解决。
def twoSum(nums, target):
hashmap={}
for i,num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [i,hashmap.get(target - num)]
hashmap[num] = i
#这句不能放在if语句之前,解决list中有重复值或target-num=num的情况
耗时60ms
java两数之和版本:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] index = new int[2];
for(int i=0; i<nums.length; i++){
/*
思路:map键为数组的值,map值为数组的序列
target-本次取到的数组的值可以得到一个目标值,如9-2=7
将目标值作为键,去得到map值
如果map值不存在,则目标值不是已加入数组的值
若map值存在,则map值就是我们找的数组序列
*/
if(map.get(target-nums[i]) != null){
index[0] = map.get(target-nums[i]);
index[1] = i;
return index;
}
//键为数组的值,值为数组的序列
map.put(nums[i], i);//这句放下面就避免了与自己重复
}
return index;
}
}