Skip to content

Commit 433d47a

Browse files
authored
Merge pull request #552 from adamMRamos/feat/scala/1-two-sum
scala/1-two-sum
2 parents 05e80bf + 1dad0d5 commit 433d47a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

scala/1-Two-Sum.scala

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import scala.collection.mutable
2+
3+
object Solution {
4+
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
5+
val numsWithIndex = nums.zipWithIndex
6+
val targets = numsWithIndex.toMap
7+
8+
def compliment(v: Int): Option[Int] = targets.get(target - v)
9+
10+
numsWithIndex
11+
.find { case (v, i) => !compliment(v).forall(_ == i) }
12+
.map { case (v, i) => Array(i, compliment(v).get) }
13+
.orNull
14+
}
15+
16+
/**
17+
* Optimization of above solution to do it in "one pass"
18+
* i.e. build the map as we traverse the input collection
19+
*/
20+
def twoSumOnePass(nums: Array[Int], target: Int): Array[Int] = {
21+
val targets = mutable.Map[Int, Int]()
22+
23+
for ((v, i) <- nums.zipWithIndex) {
24+
val answer = targets.get(target - v).map(Array(_, i))
25+
26+
if (answer.nonEmpty)
27+
return answer.get
28+
29+
targets.put(v, i)
30+
}
31+
32+
null
33+
}
34+
}

0 commit comments

Comments
 (0)