Hard Time in understanding the Scala code which returns indices of the two numbers

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-30 10:58:08

问题


I am having a hard time understanding m.get and m+(x._1 -> x._2) in below code ,can anyone let me know what does it do

object Solution {
    def twoSum(nums: Array[Int], target: Int): Array[Int] = {
      nums.zipWithIndex.foldLeft(Map.empty[Int,Int])((m,x)=>
      {
          if(m.get(target - x._1)==None)
              m+(x._1 -> x._2)
        else
            return Array(m.getOrElse(target-x._1, -1), x._2)
    })
    null
  }
}

This code returns indices of the two numbers such that they add up to a specific target.


回答1:


Here are a few different (better?) ways to get the same result (essentially the same).

If you want all index pairs whose values sum to the target.

def twoSum(nums :Array[Int], target :Int) :Iterator[Seq[Int]] =
  nums.indices
      .combinations(2)
      .filter{case Seq(a,b) => nums(a) + nums(b) == target}

twoSum(Array(3,5,11,2,13,9), 41)  //returns empty Iterator
twoSum(Array(3,5,11,2,13,9), 14)  //returns Iterator(Seq(0, 2), Seq(1, 5))

If you want just the first pair that sum to the target (with early termination).

def twoSum(nums :Array[Int], target :Int) :Option[Seq[Int]] =
  nums.indices
      .combinations(2)
      .find{case Seq(a,b) => nums(a) + nums(b) == target}

twoSum(Array(3,5,11,2,13,9), 41)  //returns None
twoSum(Array(3,5,11,2,13,9), 14)  //returns Some(Seq(0, 2))

If you want to avoid the Option and just return an empty collection if no 2 values sum to the target.

def twoSum(nums :Array[Int], target :Int) :Seq[Int] =
  nums.indices
      .combinations(2)
      .find{case Seq(a,b) => nums(a) + nums(b) == target}
      .getOrElse(Seq())

twoSum(Array(3,5,11,2,13,9), 41)  //returns Seq()
twoSum(Array(3,5,11,2,13,9), 14)  //returns Seq(0, 2)



回答2:


Here is a more efficient and idiomatic way to solve that problem.

def twoSum(nums: ArraySeq[Int], target: Int): Option[(Int, Int)] = {
  val allIndexes = for {
    i <- Iterator.range(start = 0, end = nums.length)
    j <- Iterator.range(start = i + 1, end = nums.length)
  } yield i -> j

  allIndexes.find {
    case (i, j) => (nums(i) + nums(j)) == target
  }
}

(Note: ArraySeq is like any normal array, but it is immutable, it was introduced in 2.13 if you are in an older version, just use a regular Array).



来源:https://stackoverflow.com/questions/59620796/hard-time-in-understanding-the-scala-code-which-returns-indices-of-the-two-numbe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!