forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0001-two-sum.scala
34 lines (26 loc) · 862 Bytes
/
0001-two-sum.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import scala.collection.mutable
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val numsWithIndex = nums.zipWithIndex
val targets = numsWithIndex.toMap
def compliment(v: Int): Option[Int] = targets.get(target - v)
numsWithIndex
.find { case (v, i) => !compliment(v).forall(_ == i) }
.map { case (v, i) => Array(i, compliment(v).get) }
.orNull
}
/**
* Optimization of above solution to do it in "one pass"
* i.e. build the map as we traverse the input collection
*/
def twoSumOnePass(nums: Array[Int], target: Int): Array[Int] = {
val targets = mutable.Map[Int, Int]()
for ((v, i) <- nums.zipWithIndex) {
val answer = targets.get(target - v).map(Array(_, i))
if (answer.nonEmpty)
return answer.get
targets.put(v, i)
}
null
}
}