We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 9dda2be commit dd27809Copy full SHA for dd27809
cpp/0001-two-sum.cpp
@@ -11,20 +11,16 @@
11
class Solution {
12
public:
13
vector<int> twoSum(vector<int>& nums, int target) {
14
- unordered_map<int, int> m;
15
- vector<int> result;
16
-
17
- for (int i = 0; i < nums.size(); i++) {
18
- int complement = target - nums[i];
19
- if (m.find(complement) != m.end()) {
20
- result.push_back(m[complement]);
21
- result.push_back(i);
22
- break;
23
- } else {
24
- m.insert({nums[i], i});
+ int n = nums.size();
+ unordered_map<int, int> mp; // val -> index
+
+ for (int i = 0; i < n; i++) {
+ int compliment = target - nums[i];
+ if (mp.find(compliment) != mp.end()) {
+ return {mp[compliment], i};
25
}
+ mp.insert({nums[i], i});
26
27
28
- return result;
+ return {};
29
30
};
0 commit comments