题目:如果数组M*N中某个元素为0,将其所在的行与列清零.
题目很简单,注意很容易出现,数组所有的数据最终都是零,设置为0之前需要记录行列.
核心代码:
func clearZero(data:inout [[Int]]) {
var rows:[Bool] = [Bool].init(repeating: false, count: data.count)
var cols:[Bool] = [Bool].init(repeating: false, count: data[0].count)
for i in 0..<rows.count {
for j in 0..<cols.count {
if data[i][j] == 0 {
rows[i] = true
cols[j] = true
}
}
}
for i in 0..<rows.count {
for j in 0..<cols.count {
if rows[i] || cols[j] {
data[i][j] = 0
}
}
}
}
测试代码:
var clearData:[[Int]] = [[1,2,3,4,0],[5,6,7,8,9],[9,10,11,12,1],[13,14,15,16,17]]
myString.clearZero(data: &clearData)
print("FlyElephant--数组清零--\(clearData)")