首页 > 代码库 > 【LeetCode】1.The Sum

【LeetCode】1.The Sum

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].

返回一个整形数组的两个索引,他们对应的数之和等于指定的目标值。

你可以假设这个目标值一定有解,但是不能使用数组中同一个数两次。

例如 nums=[2,7,11,15],target=9. 因为nums[0]+nums[1]=target.

所以return [0,1].

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         unordered_map<int,int> hash;
 5         vector<int> result;
 6         for(int i=0;i<nums.size();++i){
 7             int theRest=target-nums[i];
 8             if(hash.find(theRest)!=hash.end()){
 9                 result.push_back(hash[theRest]);
10                 result.push_back(i);
11                 return result;
12             }
13             hash[nums[i]]=i;
14         }
15         return result;
16     }
17 };

 

【LeetCode】1.The Sum