- Leetcode 3071. Minimum Operations to Write the Letter Y on a Grid
- 1. 解题思路
- 2. 代码实现
- 题目链接:3071. Minimum Operations to Write the Letter Y on a Grid
1. 解题思路
这一题思路上也是比较直接的,就是首先找到这个Y字符,然后统计一下Y字符内外各自的元素的数目,然后考察将其调整为两个不同的数字所需要改变的数据个数。
对于前者,我们只需给出Y的位置判断即可,对于后者,我们只需要用总的 n × n n\times n n×n个元素减去原本就满足条件的元素个数就是需要调整的元素个数。
2. 代码实现
给出python代码实现如下:
class Solution:def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int:n = len(grid)def is_inside_y(i, j):if i < n//2:return j == i or i+j == n-1else:return j == n // 2inside = defaultdict(int)outside = defaultdict(int)for i in range(n):for j in range(n):if is_inside_y(i, j):inside[grid[i][j]] += 1else:outside[grid[i][j]] += 1s = n*nreturn min(s-inside[i]-outside[j] if i != j else s+1 for i in range(3) for j in range(3))
提交代码评测得到:耗时374ms,占用内存16.6MB。