Search a 2D Matrix II
ID: 38; medium; 搜索二维矩阵(二)
Solution 1 (Java)
public class Solution {
/**
* @param matrix: A list of lists of integers
* @param target: An integer you want to search in matrix
* @return: An integer indicate the total occurrence of target in the given matrix
*/
public int searchMatrix(int[][] matrix, int target) {
int row = 0, col = matrix[0].length - 1;
int targetCount = 0;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) {
targetCount++;
row++;
col--;
} else if (matrix[row][col] < target) {
row++;
} else {
col--;
}
}
return targetCount;
}
}Notes
Last updated