ps:对于存在重复元素的情况,用一遍哈希和两遍哈希确实会得到不同的结果,但是都是符合题目要求的。 题目描述确实有点含糊,但是这个题目的本意是让我们练习哈希表,题目说到You may assume that each input would have exactly one solution,即您可以假设每个输入都只有一个解决方案。
两遍哈希 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution {public : vector <int > twoSum (vector <int >& nums, int target) { unordered_map <int ,int > m; for (int i = 0 ; i<nums.size(); i++) m[nums[i]] = i; for (int i = 0 ; i<nums.size(); i++) { if (m.find(target-nums[i]) != m.end() && m[target-nums[i]] != i) return {i, m[target-nums[i]]}; } return {}; } };
一遍哈希 1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution {public : vector <int > twoSum (vector <int >& nums, int target) { unordered_map <int ,int > m; for (int i = 0 ; i < nums.size(); i++) { if (m.find(target-nums[i]) != m.end()) return {m[target-nums[i]], i}; m[nums[i]] = i; } return {}; } };
暴力解法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution {public : vector <int > twoSum (vector <int >& nums, int target) { 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) return {i,j}; } return {}; } };