标签:length 商业 矩阵 == problems get sorted targe fir
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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
要求在一个二维矩阵找出目标数。借鉴其中一个题解的做法,从右上角开始遍历,目标数比右上角的数大,证明不在当前一行,行数+1;目标数比右上角的数小,证明不在当前一列,列数-1:
public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0) { return false; } int row = 0; int col = matrix[0].length - 1; int length = matrix.length; while(row < length && col >= 0) { if(matrix[row][col] == target) { return true; } else if(matrix[row][col] < target) { row++; } else { col--; } } return false; }
标签:length 商业 矩阵 == problems get sorted targe fir
原文地址:https://www.cnblogs.com/WakingShaw/p/11518217.html