leetcode_输入一个数组,目标树,检查目标是数组下标的哪两个之和,不准重复

今天是leetcode第一天,但是不太顺利。做这些,想不到

原题目:

我给的答案:

 1 class Solution {
 2 public:
 3     vector<int>  twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         for( int i = 0; i <nums.size() ; i ++){
 6             for( int j = i+1; j <nums.size() ; j ++){
 7                 if( nums[i] + nums[j] == target){
 8                     result.push_back(i);   //首先没有想到要把计算出来的数组的下标传到一个vector中,失败
 9                     result.push_back(j);
10                     return result;
11                 }
12                    
13             }
14         }
15         return result;
16     }
17 }; 
首先没有想到要把计算出来的数组的下标传到一个vector中,失败
其次,这个的计算复杂度特别大,很显然不符合公司要求的标准。
然后看人家的答案觉得人家的确实好
 1 class Solution {
 2 public:
 3    
 4 
 5      vector<int> twoSum(vector<int> &numbers, int target){
 6      unordered_map<int , int> hash;
 7          vector<int> result;
 8          for(int i = 0 ; i < numbers.size(); i++){
 9              int number_find = target - numbers[i];
10              
11              if( hash.find(number_find)!= hash.end()){  //find函数的复杂度是常量级别的
12                  result.push_back( hash[number_find] );
13                  result.push_back(i);
14                  return  result ;
15              }
16                 hash[numbers[i]] = i; // 这一步是完成numbers 到hash的复制,且避免重复
17          
18         }  
19                 return result;
20     }
21 
22 };
原文地址:https://www.cnblogs.com/xiaochige/p/7739901.html