We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent b9c205f commit 1745d8fCopy full SHA for 1745d8f
C++/two-sum.cpp
@@ -14,4 +14,28 @@ class Solution {
14
}
15
return v;
16
17
-};
+};
18
+
19
+Above solution is of O(n^2) time complexity
20
21
+//O(n) time complexity
22
+//O(n) space complexity
23
24
25
+vector<int> twoSum(vector<int> &numbers, int target)
26
+{
27
+ //Key is the number and value is its index in the vector.
28
+ unordered_map<int, int> hash;
29
+ // make a vector final result
30
+ vector<int> finalresult;
31
+ for (int i = 0; i < numbers.size(); i++) {
32
+ int n = target - numbers[i];
33
34
+ //if n is found in map, return them
35
+ if (hash.find(n) != hash.end()) {
36
+ result.push_back(hash[n] + 1);
37
+ result.push_back(i + 1);
38
+ return finalresult;
39
+ }
40
+}
41
0 commit comments