看题解发现有一个解法是
class RemoveElement {
func removeElement(inout nums: [Int], _ val: Int) -> Int {
nums = nums.filter { (num) in num != val }
return nums.count
}
}
查了一下 filter()这个函数:
Use filter to loop over a collection and return an Array containing only those elements that match an include condition.
The filter method has a single argument that specifies the include condition. This is a closure that takes as an argument the element from the collection and must return a
Boolindicating if the item should be included in the result.
总结来说就是遍历数组,然后返回符合闭包里的判定条件的结果。
let digits = [1,4,1015]
let even = digits.filter{$0 % 2 == 0}
// [4, 10]