在Scala中移动零

时间:2017-08-15 14:15:59

标签: arrays algorithm scala

我正在使用scala处理leetcode的“Move Zeroes”。 https://leetcode.com/problems/move-zeroes/description/ 给定一个数组nums,写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序。您必须就地执行此操作,而无需复制阵列。

我有一个在IntelliJ中运行良好的解决方案但是在Leetcode中执行时输入相同的数组,我也不确定它是否就地完成...我的代码有问题吗?

由于

def moveZeroes(nums: Array[Int]): Array[Int] = {
    val lengthOrig = nums.length
    val lengthFilfter = nums.filter(_ != 0).length
    var numsWithoutZero = nums.filter(_ != 0)
    var numZero = lengthOrig - lengthFilfter

    while (numZero > 0){
       numsWithoutZero = numsWithoutZero :+ 0
       numZero = numZero - 1
    }
    numsWithoutZero
}

还有一件事:leetcode给出的模板代码返回Unit类型但是我的返回Array。

def moveZeroes(nums: Array[Int]): Unit = {

}

2 个答案:

答案 0 :(得分:2)

虽然我同意@ayush,但Leetcode明确要求您使用可变状态。您需要更新输入数组以使其包含更改。此外,他们要求您在最少的操作中执行此操作。

所以,虽然不是惯用的Scala代码,但我建议你解决这些问题:

def moveZeroes(nums: Array[Int]): Unit = {
    var i = 0
    var lastNonZeroFoundAt = 0
    while (i < nums.size) {
        if(nums(i) != 0) {
          nums(lastNonZeroFoundAt) = nums(i)
          lastNonZeroFoundAt += 1
        }
        i += 1

    i = lastNonZeroFoundAt
    while(i < nums.size) {
        nums(i) = 0
        i += 1
    }
}

由于这是非惯用的Scala,因此不鼓励编写此类代码,因此有点难以阅读。解决方案中显示的C ++版本实际上可能更容易阅读并帮助您理解上面的代码:

void moveZeroes(vector<int>& nums) {
    int lastNonZeroFoundAt = 0;
    // If the current element is not 0, then we need to
    // append it just in front of last non 0 element we found. 
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] != 0) {
            nums[lastNonZeroFoundAt++] = nums[i];
        }
    }
    // After we have finished processing new elements,
    // all the non-zero elements are already at beginning of array.
    // We just need to fill remaining array with 0's.
    for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
        nums[i] = 0;
    }
}

答案 1 :(得分:1)

你的答案在LeetCode中给出了TLE(超出时间限制)错误。我不知道发生这种情况的条件是什么。但是我看到你的代码中有很多东西不完美。

纯函数式编程不鼓励使用任何可变状态,而是专注于将val用于所有内容

我会这样试试 -

def moveZeroes(nums: Array[Int]): Array[Int] = {
    val nonZero =  nums.filter(_ != 0)
    val numZero = nums.length - nonZero.length
    val zeros =  Array.fill(numZero){0}
    nonZero ++ zeros
}  

P.S - 这也在Leetcode中提供了TLE,但我仍然认为在功能方面它更好......虽然可以用于评论。