Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解题思路:
这个题一开始,想要直接用暴力方法,对每一组数字进行遍历,但是这个方法的时间复杂度太高了O(n^2).所以我想了想,用python做的话,可以用字典,将数组放入字典中作为key,然后计算target-key得到满足题意所需的数,当这个数能在字典的key中找到,就说明有,就输出对应的位置。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
newnum={}
count=0
for number in nums:
neednum=target-number
if neednum in newnum:
return (newnum[neednum], count)
newnum[number]=count
count+=1
做完了以后,在Solution里边看到有个更加简洁的方法,不需要申请字典dict,直接target-a,判断nums里边是否存在这个数,有的话输出位置。
index = 0
while(nums):
a = nums.pop(0)
b = target - a
if b in nums:
return [index, nums.index(b)+index+1]
index += 1
C++版:
因为python的方法是用dict,所以想到在c++中也可以用类似的结构。在STL中有个map容器,也是key-value结构,所以可以 用上边的python版相同的思路来解决问题。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
map<int,int> m;
for(int i=0;i<nums.size();i++)
{
if(m.find(target-nums[i])!=m.end())
{
ret.push_back(m[target-nums[i]]);
ret.push_back(i);
}
m[nums[i]]=i;
}
return ret;
}
};