題目:如果數(shù)組M*N中某個(gè)元素為0觉渴,將其所在的行與列清零.
題目很簡(jiǎn)單检痰,注意很容易出現(xiàn)愤惰,數(shù)組所有的數(shù)據(jù)最終都是零苇经,設(shè)置為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
}
}
}
}
測(cè)試代碼:
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--數(shù)組清零--\(clearData)")