zoukankan      html  css  js  c++  java
  • 1351. Count Negative Numbers in a Sorted Matrix

    Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. 

    Return the number of negative numbers in grid.

    每行是不递减的顺序,每列也是不递减的顺序,统计有多少格子是负数

    n2方法 两层for循环

    nlog方法 对每一行做二分搜索

    class Solution(object):
        def countNegatives(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            cnt = 0
            for row in grid:
                l = 0
                r = len(row) - 1
                while l <= r:
                    mid = (l + r) // 2
                    if row[mid] < 0:
                        r = mid - 1
                    else:
                        l = mid + 1
                cnt += len(row) - l
            return cnt
                
            

    n+m方法 利用行列都是有序的性质,从最左下角开始,每行先往右走,找到第一个负数的位置,然后统计一下,然后往上一行继续重复之前的操作。

    class Solution(object):
        def countNegatives(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            cnt = 0
            n = len(grid)
            m = len(grid[0])
            row = n - 1
            col = 0
            while row >= 0:
                while col < m:
                    if grid[row][col] >= 0:
                        col += 1
                    else:
                        break
                cnt += m - col
                row -= 1
            return cnt
                
            
  • 相关阅读:
    jar-下载站点
    java-原生爬虫机制源码
    eclipse-插件安装的三种方式
    ivy,ivyde插件-eclipse
    cygwin-介绍-安装
    cygwin-使用介绍
    linux-命令全集
    jquery-遍历each
    SSD固态硬盘的闪存芯片颗粒介绍
    java-测试synchronized使用xxx.class和this使用的区别
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13207046.html
Copyright © 2011-2022 走看看