Type:easy
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].
本題給定一個(gè)int型nums數(shù)組以及一個(gè)int型target值漆弄。求問在nums數(shù)組中是否有兩個(gè)值相加等于target沿彭。
首先我們建立一個(gè)unordered_map<int, int>型unordered_map让禀,其中key值為nums數(shù)組中某一位具體數(shù)值辈末,value值為其序列震嫉,如map[2] = 0。
遍歷讀取整個(gè)nums數(shù)組售貌,計(jì)算target-nums[i]的值為complement砚殿,使用map.find() ==?map.end()查找方式對(duì)整個(gè)map查找complement值芽死,若能查找到,則map.find(complement) != map.end()雹拄。此時(shí)等于target的兩個(gè)int型分別為complement及nums[i]收奔,則應(yīng)返回的序列為map[complement]及i。若未查找到滓玖,則返回為空坪哄。
附代碼:
class Solution {
public:
? ? vector<int> twoSum(vector<int>& nums, int target) {
? ? ? ? unordered_map<int, int> map;
? ? ? ? for(int i =0; i< nums.size(); i++){
? ? ? ? ? ? int complement = target - nums[i];
? ? ? ? ? ? if(map.find(complement) != map.end()){
? ? ? ? ? ? ? ? return {map[complement], i};
? ? ? ? ? ? ? }
? ? ? ? ? ? ? map[nums[i]] = i;
? ? ? ? }?
? ? ? ? return {};
? ? }
};