38.Search a 2D Matrix II (0(M+N)

2017-06-28  本文已影响0人  博瑜
public class Solution {
/**
 * @param matrix: A list of lists of integers
 * @param: A number you want to search in the matrix
 * @return: An integer indicate the occurrence of target in the given matrix
 */
public int searchMatrix(int[][] matrix, int target) {
    // write your code here
    if (matrix == null) return 0;
    int row = matrix.length;
    if (row == 0) return 0;
    int column = matrix[0].length;
    int currentRow = row - 1;
    int currentColumn = 0;
    int result = 0;
    while (currentRow >= 0 && currentColumn <= column - 1) {
        if (matrix[currentRow][currentColumn] == target) {
            result++;
            currentRow--;
        } else if (matrix[currentRow][currentColumn] < target) {
            currentColumn++;
        } else {
            currentRow--;
        }
    }
    return result;
}
}
上一篇 下一篇

猜你喜欢

热点阅读