LeetCode # 1 simple question

Title: Given an array of integers  nums and a target value  target, and you figure out a target value of the two integers in the array, and return to their array subscript.

Solution: Simple question, nothing to say, do not want the n- 2  complexity out, map it to keep it logn

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         std::map<int, int> numMap;
 5         vector<int> ans;
 6         for (int i = 0; i < nums.size(); ++i){
 7             if (numMap.find(target - nums[i]) != numMap.end()){
 8                 ans.push_back(numMap[target - nums[i]]);
 9                 ans.push_back(i);
10                 return ans;
11             }
12             numMap[nums[i]] = i;
13         }
14         return ans;
15     }
16 };

 

Guess you like

Origin www.cnblogs.com/error408/p/11546236.html