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

    Search a 2D Matrix II

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

    • Integers in each row are sorted in ascending from left to right.
    • Integers in each column are sorted in ascending from top to bottom.

    For example,

    Consider the following matrix:

    [
      [1,   4,  7, 11, 15],
      [2,   5,  8, 12, 19],
      [3,   6,  9, 16, 22],
      [10, 13, 14, 17, 24],
      [18, 21, 23, 26, 30]
    ]
    

    Given target = 5, return true.

    Given target = 20, return false.

    https://leetcode.com/problems/search-a-2d-matrix-ii/
     
     
     
     

     
     
    从右上角开始,如果当前的数大于target,列号减一(左移一列),如果当前的数小于target,行号加一(下移一行)。
    从左下角开始找也是一样的。
     1 /**
     2  * @param {number[][]} matrix
     3  * @param {number} target
     4  * @return {boolean}
     5  */
     6 var searchMatrix = function(matrix, target) {
     7     return findTarget(0, matrix[0].length - 1);
     8 
     9     function findTarget(i, j){
    10         if(matrix[i][j] === target){
    11             return true;
    12         }
    13         if(matrix[i][j] > target){
    14             if(!matrix[i][j - 1]){
    15                 return false;
    16             }else{
    17                 return findTarget(i, j - 1);
    18             }
    19         }
    20         if(matrix[i][j] < target){
    21             if(!matrix[i + 1]){
    22                 return false;
    23             }else{
    24                 return findTarget(i + 1, j);
    25             }
    26         }
    27     }
    28 };
  • 相关阅读:
    Alpha 冲刺报告6
    课堂小测(同学录)
    Alpha 冲刺报告5
    alphe4
    Alpha 冲刺报告3
    软件工程实践2017第二次作业
    软件工程实践2017第一次作业
    面向对象程序设计 第六次作业
    1025 反转链表(待完善)
    面向对象程序设计 第五次作业
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4676195.html
Copyright © 2011-2022 走看看