Scala solutions

  • 0

    This one has a cleaner result type than Array[Int] suggested by the leetcode template, and sacrifices some cycles for a more functional approach.

      def twoSum(xs: Array[Int], target: Int): Option[(Int, Int)] = {
        val indicesByValue = xs.zipWithIndex.toMap
        val matchIndices = xs map {x => indicesByValue get (target - x)}
        val allSolutions = (xs.indices zip matchIndices) filter { case (_, m) => m.isDefined }
        allSolutions collectFirst { case (i, Some(j)) => (i, j)}

    Here is a more mainstream alternative

      def twoSum2(xs: Array[Int], target: Int): Array[Int] = {
        val indicesByValue = mutable.Map[Int, Int]()
        for (assoc @ (x, i) <- xs.zipWithIndex)
          indicesByValue get (target - x) match {
            case Some(j) => return Array(j, i)
            case None => indicesByValue += assoc
        throw new NoSuchElementException()

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.