I'm solving some online puzzles and I had this problem:
Given a vector, write code to find the indices of TWO values which sum to a given number N
so if I'm given [2, 5, 6] and N = 8, I should output the 0-based indices [0, 2].
I wrote the following code to do this in O(N)
vector<int> twoSum(vector<int>& nums, int target) {
unordered_multimap<int, int> numbers_multimap;
numbers_multimap.reserve(nums.size());
for(size_t i = 0; i < nums.size(); ++i) {
numbers_multimap.emplace(nums[i], i);
auto interval = numbers_multimap.equal_range(target - nums[i]);
for (auto it = interval.first; it != interval.second; ++it) {
int other_position = it->second;
if (other_position != i)
return vector<int>{i, other_position};
}
}
return vector<int>{};
}
and it works, but I noticed that there are faster solutions.
Since I suppose the algorithm is already quite fast, I'd like to know if there are additional pro tips to improve the runtime of this code.
std::sort
is O(NlogN) while this is O(N) \$\endgroup\$ – Dean Jun 2 '16 at 12:44