LeetCode 1 : Two Sum
阿新 • • 發佈:2018-12-15
題目:
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].
例子:
陣列:[2,7,11,15],目標:9
因為 陣列中0號元素和1號元素的和為9.
因此,返回[0,1]。
程式碼:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> m; for( int i = 0 ; i < nums.size() ; ++ i ){ int res = target - nums[i]; if( m.find( res ) == m.end() ){ m[nums[i]] = i; }else{ return { m[res] , i }; } } } };
思路:
利用HashMap來快速查詢已經訪問過的元素。