Given an array (for example, [ 1, 0, 2, 0, 0, 3, 4 ]), implement methods that moves the non-zero elements to the beginning of the array (the rest of the elements don't matter)
I have implemented as follows, it works but I wonder shorter way of doing it?
import Foundation
var inputArray = [ 1, 0, 2, 0, 0, 3, 4 ]
func remoZeros (inputArray :[Int]) -> [Int]
{
var nonZeroArray = [Int]()
var zeroArray = [Int]()
for item in inputArray
{
if item != 0
{
nonZeroArray.append(item)
}
else
{
zeroArray.append(item)
}
}
return nonZeroArray + zeroArray
}
var result = remoZeros (inputArray: inputArray)
partition(by:).inputArray.partition(by: { $0 == 0 })– note that this mutates the original array in-place rather than returning a new one.