问题
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)
回答1:
You can try
var inputArray = [ 1, 0, 2, 0, 0, 3, 4 ]
func remoZeros (inputArray :[Int]) -> [Int] {
return inputArray.filter{$0 != 0} + inputArray.filter{$0 == 0}
}
来源:https://stackoverflow.com/questions/52882611/array-manipulation-and-reordering-in-swift