題目:如果數組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)")