题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 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]
提示:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
Python3:
法一:暴力搜索
# coding=gbk
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#对nums每个元素循环
for i in range(len(nums)):
#从nums[i]的下一个开始找
for j in range(i+1,len(nums)):
#如果找到了就返回值
if nums[i]+nums[j]==target:
return i,j
法二:For循环(一次)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
if target - nums[i] in nums:
# 判断返回的两个数是否相同
if i != nums.index(target-nums[i]):
return i, nums.index(target-nums[i])
法三:Dict
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#遍历一个i,就把nums[i]放在字典里。之后i不断相加,总会碰到
#target - nums[i]在字典里的情况。碰到的时候return即可。这里注意到先return的是dict[a],再是当前的i,原因就是dict里存的value都是以前遍历过的i,所以它比当前的i小,按从小到大的顺序所以这样排。
dict = {}
for i in range(len(nums)):
temp = target - nums[i]
if temp in dict:
return dict[temp],i
else:
dict[nums[i]] = i
法四:For循环(两次)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[j] == target - nums[i]:
return i, j
break
else:
continue
Java:
法一:暴力搜索
class Solution {
public int[] twoSum(int[] nums, int target) {
int re[] = new int[2];
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(nums[i] == target-nums[j]){
re[0] = i;
re[1] = j;
}
}
}
return re;
}
}
法二:HashMap(两次for循环)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[]re = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<nums.length; i++){
map.put(nums[i], i);
}
for(int j=0; j<nums.length; j++){
int temp = target - nums[j];
if(map.containsKey(temp) && j!=map.get(temp)){
re[0] = j;
re[1] = map.get(temp);
return re;
}
}
return re;
}
}
法三:HashMap(一次for循环)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[]re = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<nums.length; i++){
if(map.containsKey(nums[i])){
return new int[] {map.get(nums[i]), i};
}
map.put(target-nums[i], i);
}
return new int[]{1,1,1};
}
}
C++:
未完。。
参考:
https://blog.csdn.net/ssswill/article/details/84824667