※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715590461.A.477.html
Re: [閒聊] 每日leetcode
看板 | Marginalman |
---|---|
作者 | SecondRun (南爹摳打) |
時間 | 2024-05-13 16:54:16 |
留言 | 0則留言 |
: https://leetcode.com/problems/score-after-flipping-matrix/description/
: 861. Score After Flipping Matrix
: 給你一個二維陣列,他可以被看成多個二進位數字,例如:
: 100 = 4
: 011 = 3
: 你可以對行或列進行翻轉把0和1交換,你可以翻轉無限次求出怎麼樣翻轉可以讓二進制
: 數的和最大。
: 思路:
: 1.觀察一下列什麼時候要翻轉,我們發現最左邊的數字如果是0翻轉一定會變大,1則一
: 定變小,所以遇到第一位為0就翻轉該列。
: 2.觀察行什麼時候要翻轉,我們可以發現如果0的數量比1多翻轉一定會變大,數有幾個0
: 如果大於1的數量就翻轉他。
: 3.把行列翻轉完的矩陣轉成十進制求和。
: py code:
: ----------------------------------------
: class Solution:
: def matrixScore(self, grid: List[List[int]]) -> int:
: m, n = len(grid), len(grid[0])
: for i in range(m):
: if grid[i][0] == 0:
: # reverse
: for j in range(n):
: grid[i][j] = (grid[i][j] + 1) % 2
: for i in range(n):
: zero = 0
: for j in range(m):
: if grid[j][i] == 0:
: zero += 1
: if zero > m // 2:
: # reverse
: for j in range(m):
: grid[j][i] = (grid[j][i] + 1) % 2
: # to binary
: res = 0
: for i in range(m):
: num = 0
: for j in range(n):
: num = num*2 + grid[i][j]
: res += num
: return res
: ----------------------------------------
: for迴圈可以壓吧 懶得想==
思路: 差不多,看圖說故事
C# code:
public class Solution
{
public int MatrixScore(int[][] grid)
{
int rowCount = grid.Length;
int colCount = grid[0].Length;
foreach (var row in grid)
{
if (row[0] == 1) continue;
for (int i = 0; i < colCount; i++)
{
row[i] ^= 1;
}
}
int score = 0;
int b = 1;
for (int i = colCount - 1; i >= 1; i--)
{
int count = 0;
for (int j = 0; j < rowCount; j++)
{
if (grid[j][i] == 1) count++;
}
score += Math.Max(count, rowCount - count) * b;
b *= 2;
}
score += rowCount * b;
return score;
}
}
--
(づ′・ω・)づ
--
※ 批踢踢實業坊(ptt.cc), 來自: 60.248.96.37 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715590461.A.477.html
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715590461.A.477.html