LC 1. Two Sum

Topic Introduction

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].


Answers

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

Supplement

Cycle into three parts:

= 1. The remaining target - now

2. Check whether the rest of the map, in the words, it shows there is an array of numbers, you can return to the index.

3. The digital map stored in

Some want to pay special attention to are:

map [key] = value -> map [num] = index, in numeric key, is stored in a content index. So, when searching for key (ie digital) basis, while the index for the results we want.

Guess you like

Origin www.cnblogs.com/kykai/p/11613923.html