-
Notifications
You must be signed in to change notification settings - Fork 43
/
twoSum.scala
52 lines (47 loc) · 1.35 KB
/
twoSum.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// V0
object Solution{
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val map = scala.collection.mutable.Map[Int, Int] ()
var count = 0
for (num <- nums){
val comp = target - num
map.get(comp) match {
case None => {map.put(num, count)}
case Some(index) => return Array(index, count)
}
count += 1
}
Array(-1,-1)
}
}
// V1
// https://leetcode.com/problems/two-sum/discuss/138/scala-on-solution
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val map = scala.collection.mutable.Map[Int, Int] ()
var count = 0;
for(num <- nums){
val comp = target-num
map.get(comp) match {
case None => {map.put(num,count)}
case Some(index) => return Array(index,count)
}
count = count+1
}
Array(0,0)
}
}
// V2
// https://leetcode.com/problems/two-sum/discuss/260824/Scala-Solution
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val withIndex = nums.zipWithIndex
val hashMap = withIndex.toMap
withIndex
.collectFirst {
case (value, index) if hashMap.get(target - value).exists(_ != index) =>
Array(index, hashMap(target - value))
}
.get
}
}