给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 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 <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
两层遍历的方式,时间复杂度为O(n^2)。
C++实现#include#include using namespace std; class Solution { public: vector temp; vector twoSum(vector & nums, int target) { if(nums.size()<2||nums.size()>1e4||target<-1e9||target>1e9) { throw new std::invalid_argument("The list is out of range"); } for(int i=0;i Python实现 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = [] for i, each in enumerate(nums): if abs(target-each) >=0 and i not in result: try: tmp = nums.index(target - each) if tmp != i: result.append(i) result.append(tmp) except: continue return result进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
C++实现
可以使用哈希表,也就是散列表,在C++中是map容器,Python就是字典。class Solution { public: vectorPython实现twoSum(vector & nums, int target) { map a;//提供一对一的hash vector b(2,-1);//用来承载结果,初始化一个大小为2,值为-1的容器b for(int i=0;i 0) { b[0]=a[target-nums[i]]; b[1]=i; break; } a[nums[i]]=i;//反过来放入map中,用来获取结果下标 } return b; }; }; class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i



