题目:
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].
解释:
题目通俗易懂,可以用字典做,把数值当做健,把index当做值。
pytho代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
for i ,val in enumerate(nums):
if target-val in dic:
return [dic[target-val],i]
dic[val]=i
c++代码:
#include<map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int>_map;
vector<int>result;
for (int i=0;i<nums.size();i++)
{
if (_map.count(target-nums[i]))
{
result={_map[target-nums[i]],i};
return result;
}
_map[nums[i]]=i;
}
}
};
总结:
把数值当做健,把index当做值。在这系列的问题中用处很大。