This is the very beginning of LeetCode, where the dream starts (or ends 🤣). Enjoy your journey!
Problem Description
1 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. |
Solution
The problem is quite simple if you just try to crack it down. The first thought is to use 2 nested for
loops, the outer loop traverses the whole array and the inner loop starts from next position of the outer pointer. When the sum of 2 values matches the target
, return the 2 pointers as an array.
1 | class Solution { |
However, this will results in O(N^2) time complexity, that is very undesirable; and the it doesn’t match the follow-up requirement as well. Let’s dive deeper to see how to solve the follow-up.
1 | class Solution { |
The std::map
is an stl container and it is implemented with red black tree. So its insertion and search are both O(log(N)). With the outer for loop, the time complexity of the code is reduced to O(N*log(N)), which meets the requirement of follow-up.
This snippet of code insert a key-value pair into std::map
in each for
loop, and check if the difference between target
and nums[i]
exists in the std::map a
. The assertion a[target-nums[i]] != i
is to avoid duplicates in the return value, since a.insert()
is before a.count()
.
And this is the end of my note. Enjoy your day!