-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSumSolution.scala
41 lines (37 loc) · 1.17 KB
/
TwoSumSolution.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
package easy
/** QUESTION: Given an array of integers nums and an integer target, return
* indices of the two numbers such that they add up to target.
*/
object TwoSumSolution {
def apply(nums: Array[Int], target: Int): Array[Int] = twoSum(nums, target)
def twoSum(nums: Array[Int], target: Int): Array[Int] =
calculateContains(nums, target)
def calculateFilter(
nums: Array[Int],
target: Int,
count: Int = 0
): Array[Int] = {
nums.headOption match
case Some(head) =>
val found = nums.tail.filter(x => head + x == target)
if (found.length > 0)
Array(count, nums.tail.indexWhere(_ == found.head) + count + 1)
else
calculateFilter(nums.tail, target, count + 1)
case None => Array(0, 0)
}
def calculateContains(
nums: Array[Int],
target: Int,
count: Int = 0
): Array[Int] = {
nums.headOption match
case Some(head) =>
val needle = target - head
if (nums.tail.contains(needle))
Array(count, nums.tail.indexWhere(_ == needle) + count + 1)
else
calculateContains(nums.tail, target, count + 1)
case None => Array(0, 0)
}
}