# 【LeetCode】 1. Two Sum ## Description > 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]. ``` ## Solution * 使用hash table的做法加速,只需要跑一次for loop即可解決。 * 以測資為例,第一個遇到`2`且目標為`9`,將第`7(9-2)`格放入`0`,意思是之後遇到`7`時,去找第`7`格就知道要跟哪一格相加了。 ### Code ```C++=1 class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; unordered_map<int,int> hash; for (int i = 0;i<nums.size();i++) { if(hash.find(nums[i]) != hash.end()) { ans.push_back(i); ans.push_back(hash[nums[i]]); return ans; } hash[target-nums[i]]=i; } return ans; } }; ``` ###### tags: `LeetCode` `C++`