Skip to content

Commit 1745d8f

Browse files
improved c++ code (#161)
1 parent b9c205f commit 1745d8f

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Diff for: C++/two-sum.cpp

+25-1
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,28 @@ class Solution {
1414
}
1515
return v;
1616
}
17-
};
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

Comments
 (0)