I practice Scala by solving algo questions and stuck on this problem from leetcode:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
I came up with the following code
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val map = scala.collection.mutable.Map.empty[Int, Int]
nums.zipWithIndex.foreach{ case(num, idx) =>
map.get(idx) match {
case Some(r) => return Array(r, idx)
case None => map += (idx -> (target-num))
}
}
Array(-1, -1)
}
It seems that the I'm adding values to map in a wrong way, as for every input I get an Array(-1,-1) as a result.
The expected soultion.
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
var map = Map.empty[Int, Int]
for ((v, i) <- nums.zipWithIndex) {
map.get(v) match {
case Some(r) => return Array(r, i)
case None => map ++= Map((target - v) -> i)
}
}
Array(-1, -1)
}
Can you point on my mistake and explain how to update hashMap properly? While updating the elements with mutable Map I was referencing this post.