Skip to content

Instantly share code, notes, and snippets.

@mlivingston40
Last active April 29, 2024 20:10
Show Gist options
  • Save mlivingston40/789e4cf5206b4edf34f46de072f3ff66 to your computer and use it in GitHub Desktop.
Save mlivingston40/789e4cf5206b4edf34f46de072f3ff66 to your computer and use it in GitHub Desktop.
two sum scala
//import org.json4s.DefaultFormats.++
//import org.json4s.JsonDSL.int2jvalue
object Solution extends App {
def twoSum(nums: Array[Int], target: Int): Option[Array[Int]] = {
var leftIndex: Int = 0
while (leftIndex < nums.length -1) {
println("*****")
println("The leftIndex: ")
println(leftIndex)
val leftValue: Int = nums(leftIndex)
var rightIndex: Int = leftIndex + 1
for (r <- nums.takeRight(nums.length - rightIndex)) {
println("The rightIndex: ")
println(rightIndex)
if (r + leftValue == target)
{
println("The leftValue: ")
println(leftValue)
println("The r: ")
println(r)
return Some(Array(leftIndex, rightIndex))
} else {
// update the rightIndex
rightIndex = rightIndex + 1
}
}
// update the left index
leftIndex = leftIndex + 1
}
None
}
// test cases
val numsTest: Array[Int] = Array(2, 15, 11, 7)
val outArrayOption = twoSum(numsTest, 9)
println(outArrayOption)
val outArray: Array[Int] = outArrayOption match {
case Some(n) =>
n
}
println(outArray.mkString("Array(", ", ", ")"))
}
// another way
/*
import scala.util.boundary, boundary.break
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
var leftIndex: Int = 0
boundary:
while (leftIndex < nums.length -1) {
val leftValue: Int = nums(leftIndex)
var rightIndex: Int = leftIndex + 1
for (r <- nums.takeRight(nums.length - rightIndex)) {
if (r + leftValue == target)
break(Array(leftIndex, rightIndex))
else
rightIndex = rightIndex + 1
}
// update the left index
leftIndex = leftIndex + 1
}
Array(-1,-1)
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment