leetCode刷题第一题(两数之和)

C++代码:
#include <iostream> #include <vector> #include <unordered_map> using namespace std; vector<int> twoSum(const vector<int>& nums, int target) { unordered_map<int, int> hashtable; //key为num,value是num对应的下标 for (int i = 0; i < nums.size(); ++i) { auto it = hashtable.find(target - nums[i]); if (it != hashtable.end()) { return { it->second, i }; } hashtable[nums[i]] = i; } return {}; } int main() { //这里并不是像leetCode上的一样只是写核心代码,也模拟输入。 //输入的第一行是输入的数组 //第二行是输入的目标值 vector<int> nums; int num; while (cin >> num) { nums.push_back(num); if (cin.get() == '\n') //以换行符作为结束条件,有的机试上就被这个坑过。 { break; } } int target; cin >> target; vector<int> result = twoSum(nums, target); cout << result[0] << " " << result[1] << endl; return 0; }
posted on 2021-07-11 14:08 xcxfury001 阅读(37) 评论(0) 收藏 举报
 
                     
                    
                 
                    
                 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号