Leetcode 10: Two sum
Problem statement: given an array of integers nums
and an integer target
, return the indices i
and j
such that nums[i] + nums[j] == target
and i != j
. You may assume that every input has exactly one pair of indices i
and j
that satisfy the condition. Return the answer with the smaller index first.
Let’s do some thinking. The obvious answer would be to have two nested loops and iterate over nums
while checking when the sum equals target
, but that’s too easy so surely there must be a better way. We can treat our condition as we would any other equation and do:
$$ \text{nums}[i] + \text{nums}[j] = \text{target} \Leftrightarrow \text{nums}[j] = \text{target} - \text{nums}[i] $$
This means that, if we iterate over nums
while calculating the above difference and saving it in a hashmap, if we ever find ourselves in the situation where the difference is already stored as a key in the hashmap, it means that we have found the value that satisfies the above equation together with the value used as a key in the hashmap. Thus, just associate these keys with the index they were calculated from and return the values in the appropriate format when a matching key is found.
|
|