Array Manipulation and reordering in Swift

╄→гoц情女王★ 提交于 2020-01-05 15:03:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!