From 1dad0d51cd129e61e9a161e29bac8c3f9f3f065a Mon Sep 17 00:00:00 2001 From: Adam Ramos Date: Wed, 20 Jul 2022 12:18:31 -0400 Subject: [PATCH] feat: add scala solution for 1. two sum --- scala/1-Two-Sum.scala | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 scala/1-Two-Sum.scala diff --git a/scala/1-Two-Sum.scala b/scala/1-Two-Sum.scala new file mode 100644 index 000000000..2ea9c3129 --- /dev/null +++ b/scala/1-Two-Sum.scala @@ -0,0 +1,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 + } +} \ No newline at end of file