Leetcode 3128. Right Triangles

  • [Leetcode 3128. Right Triangles](#Leetcode 3128. Right Triangles)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话对于任意一个位置,如果该位置为1,假设其所在行中1的个数 r i r_i ri,所在列中1的个数为 c j c_j cj,那么以该位置作为三角形顶点的三角形的个数就是 ( r i − 1 ) ⋅ ( c j − 1 ) (r_i-1)\cdot(c_j-1) (ri−1)⋅(cj−1),因此,我们只需要先求出所有行和列当中的1的个数,然后遍历一下所有1的位置,将对应的三角形个数相加即可得到最终的答案。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def numberOfRightTriangles(self, grid: List[List[int]]) -> int:
        n, m = len(grid), len(grid[0])
        rows = [sum(line) for line in grid]
        cols = [sum([grid[i][j] for i in range(n)]) for j in range(m)]
        ans = 0
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 0:
                    continue
                ans += (rows[i]-1) * (cols[j]-1)
        return ans

提交代码评测得到:耗时2234ms,占用内存37.7MB。

相关推荐
Espresso Macchiato1 个月前
Leetcode 3316. Find Maximum Removals From Source String
leetcode·动态规划·leetcode medium·leetcode 3316·leetcode双周赛141
Espresso Macchiato2 个月前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
Espresso Macchiato2 个月前
Leetcode 3301. Maximize the Total Height of Unique Towers
leetcode·leetcode medium·leetcode双周赛140·leetcode 3301
Espresso Macchiato2 个月前
Leetcode 3302. Find the Lexicographically Smallest Valid Sequence
leetcode medium·lcs·leetcode 3302·leetcode双周赛140·最大公共子序列
Espresso Macchiato3 个月前
Leetcode 3255. Find the Power of K-Size Subarrays II
leetcode·leetcode medium·leetcode 3255·leetcode 3254·leetcode周赛137
Espresso Macchiato4 个月前
Leetcode 3240. Minimum Number of Flips to Make Binary Grid Palindromic II
leetcode·leetcode medium·回文·leetcode 3240·leetcode双周赛136
Espresso Macchiato4 个月前
Leetcode 3234. Count the Number of Substrings With Dominant Ones
排列组合·leetcode medium·容斥原理·leetcode 3234·leetcode周赛408
Espresso Macchiato5 个月前
Leetcode 3201. Find the Maximum Length of Valid Subsequence I
leetcode medium·leetcode题解·leetcode 3201·leetcode周赛404
Espresso Macchiato5 个月前
Leetcode 3196. Maximize Total Cost of Alternating Subarrays
leetcode·动态规划·leetcode medium·leetcode周赛403·leetcode 3196
Espresso Macchiato5 个月前
Leetcode 3195. Find the Minimum Area to Cover All Ones I
leetcode·leetcode medium·leetcode题解·leetcode 3195·leetcode周赛403