Doing something you intrinsically are enthusiastic with.

2016年8月22日 星期一

Leetcode - Two sum

凌晨3:23 Posted by Unknown No comments
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Solution: Using Hashmap in C++

The core idea is to see where there is the value 「Target-nums[i]」in the hashmap.

For example : Now the index is in "0" and nums[0] is 2, if there is a solution pair with nums[0]

in the future, the other value should be Target-nums[0] =7. So we will search the Target-nums[i]

value before we insert new elements to the hashmap.

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



0 意見:

張貼留言