code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int,int> hashtable; int len = nums.size(); for (int i = 0;i < len;i++) { int temp = target-nums[i]; if (hashtable.find(temp) != hashtable.end()) { return {hashtable[temp],i}; } hashtable[nums[i]] = i; } return {}; } };
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::vector<int> ret; int len = nums.size(); for (int i = 0;i < len-1;i++) { for (int j = i+1;j < len;j++) { if (nums[i] + nums[j] == target) { ret.push_back(i); ret.push_back(j); return ret; } } } return ret; } };
|
summary:
1.c++的哈希表用了动态数组的方式和哈希函数组成
2.插入可以用pair函数 也可以写成 nums_map.insert({nums[i],i}); 用初始化列表的方式