leetcode 861 [medium]
中:翻转矩阵后的得分
英:Score After Flipping Matrix
题解
1. 思路:贪心
- 旋转行使得第一列全为1
- 旋转列使得每列1最多
2. 时间复杂度:O(n * m)
- n: 行数;m:列数
- 第一次遍历完成 “旋转行使得第一列全为1”;同时统计每一列1的个数
- 第二次遍历完成 “旋转列使得每列1最多”
3. 空间复杂度:O(m)
- 第一次遍历后记录每一列1的个数
4. 实现
/**
* @param {number[][]} A
* @return {number}
*/
var matrixScore = function(A) {
// 预处理
let rowLen = A.length; // 行数
let columnLen = A[0].length; // 列数
// 行旋转,列统计
let columnOneCount = Array.from({length: columnLen}, v=>0);
for(let i=0; i<rowLen; i++){
if(A[i][0] !== 1) {
for(let j=0; j<columnLen; j++){
// 行旋转
A[i][j] = (A[i][j] + 1) % 2;
// 列统计
A[i][j] === 1 && columnOneCount[j]++;
}
}
else{
for(let j=0; j<columnLen; j++){
// 列统计
A[i][j] === 1 && columnOneCount[j]++;
}
}
}
// 列旋转
let shouldHave = Math.ceil(rowLen / 2)
for(let j=0; j<columnLen; j++){
if(columnOneCount[j] < shouldHave){
for(let i=0; i<rowLen; i++){
// 列旋转
A[i][j] = (A[i][j] + 1) % 2;
}
}
}
// 计算结果
return A.reduce((pre, curr) => {
return pre + parseInt(curr.join(''), 2);
}, 0)
};