问题
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