Move Zeroes

Posted on By ᵇᵒ

LeetCode 283

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.

fun moveZeroes(nums: IntArray): Unit {
    var index = 0
    for(i in nums.indices){
        if (nums[i] != 0){
            nums[index++] = nums[i]
        }
    }
    for (i in index until nums.size){
        nums[i] = 0
    }
}
fun moveZeroes(nums: IntArray): Unit {
    var index = 0
    for(i in nums.indices){
        if (nums[i] != 0){
            nums[index] = nums[i].apply { nums[i] = nums[index] }
            index++
        }
    }
}
fun moveZeroes(nums: IntArray): Unit {
    var index = 0
    for(i in nums.indices){
        if (nums[i] != 0){
            if(i > index){
                nums[index] = nums[i].apply { nums[i] = nums[index] }
            }
            index++
        }
    }
}
fun moveZeroes(nums: IntArray): Unit {
    var index = 0
    for(i in nums.indices){
        if (nums[i] != 0){
            if(i > index){
                nums[index] = nums[i]
                nums[i] = 0
            }
            index++
        }
    }
}