LeetCode C++:HashTable篇

发布时间 2023-06-27 17:39:33作者: karinto

1、Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         unordered_map<int, int> ret;
 5         int n = nums.size();
 6         for(int i = 0; i < n; ++i){
 7             ret[nums[i]] = i; //{元素1, 0}、{元素2, 1}, find是查找first, 不能放反
 8         }
 9         for(int i = 0; i < n; ++i){
10             auto it = ret.find(target - nums[i]);
11             if(it != ret.end() && i != it->second) //not use the same element twice
12                 return vector<int>{i, it->second}; //返回second
13         }
14         return {-1, -1};
15     }
16 };