Leetcodes Solution 1 Two Sum
匯總
雪之下雪乃:leetcode解題總匯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].
思路1
用一個map來臨時存放沒有找到匹配的數
class Solution{public: vector<int> twoSum(vector<int>& nums, int target){ //key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for(int i = 0; i < nums.size(); i++){ int numberToFind = target - nums[i]; //if numberToFind is found in map, return them if(hash.find(numberToFind) != hash.end()){ result.push_back(hash[numberToFind]); result.push_back(i); return result; } //number was not found. Put it in the map hash[nums[i]] = i; } return result; }};
推薦閱讀:
※判斷單向鏈表是否有環及求環入口的演算法數學證明
※Python數據結構與演算法刷題(1)——害死人不償命的(3n+1)猜想
※浙江大學-數據結構-選講Complete Binary Search Tree-7.3.3
※九章演算法 | Facebook 面試題:等差子序列
※2017.12.10