Swift
//func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
// // 将数据声明为var类型,否则无法对其进行操作
// var nums = nums
// // 返回值
// var count = nums.count
// // 循环次数
// var index = 0
// // 遍历数组
// for value in nums {
// // 如果数组当前值等于给定值
// if value == val {
// count -= 1
// // 移除数组中该元素
// nums.remove(at: index)
// }
// else {
// // Index+1,继续下一次循环
// index += 1
// }
// }
// print(nums)
// return count
//}
func removeElement(_ nums: [Int], _ val: Int) -> Int {
// 将数据声明为var类型,否则无法对其进行操作
var nums = nums
// 遍历数组
for value in nums {
if value == val {
if let index = nums.firstIndex(of: value) {
nums.remove(at: index)
}
}
}
print(nums)
return nums.count
}
print(removeElement([3,2,2,3], 3))
打印
[2, 2]
2
Program ended with exit code: 0