[LeetCode][JavaScript]Search a 2D Matrix II

來源:互聯網
上載者:User

標籤:

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 };

 

 

[LeetCode][JavaScript]Search a 2D Matrix II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.