zoukankan      html  css  js  c++  java
  • [LintCode] 38 Search a 2D Matrix II

    Description
    Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.

    This matrix has the following properties:

    Integers in each row are sorted from left to right.
    Integers in each column are sorted from up to bottom.
    No duplicate integers in each row or column.


    Example
    Consider the following matrix:

    [
      [1, 3, 5, 7],
      [2, 4, 7, 8],
      [3, 5, 9, 10]
    ]
    Given target = 3, return 2.

    4/27/2017

    算法班

    第17,18行的条件是同一行同一列当中没有重复的元素。

     1 public class Solution {
     2     /**
     3      * @param matrix: A list of lists of integers
     4      * @param: A number you want to search in the matrix
     5      * @return: An integer indicate the occurrence of target in the given matrix
     6      */
     7     public int searchMatrix(int[][] matrix, int target) {
     8         // write your code here
     9         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
    10             return 0;
    11         }
    12         int col = matrix[0].length - 1, row = 0;
    13         int count = 0;
    14         while  (col >= 0 && row < matrix.length) {
    15             if (matrix[row][col] == target) {
    16                 count++;
    17                 col--;
    18                 row++;
    19             } else if (matrix[row][col] < target) {
    20                 row++;
    21             } else {
    22                 col--;
    23             }
    24         }
    25         return count;
    26     }
    27 }
  • 相关阅读:
    SSM中shiro的基本使用
    TortoiseGit小乌龟 git管理工具
    vux用法
    vue webpack打包
    vue2.0 watch
    vue2.0 $emit $on组件通信
    简单工具 & 杂技
    html基础问题总结
    Node应用进程管理器pm2的使用
    node express 登录拦截器 request接口请求
  • 原文地址:https://www.cnblogs.com/panini/p/6779465.html
Copyright © 2011-2022 走看看