寫出一個高效的算法來搜索m×n矩陣中的值,返回這個值出現的次數。
這個矩陣具有以下特性:
- 每行中的整數從左到右是排序的。
- 每一列的整數從上到下是排序的。
- 在每一行或每一列中沒有重複的整數。
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) { // write your code here if (matrix == null || matrix.length == 0 || target < matrix[0][0] || target > matrix[matrix.length - 1][matrix[matrix.length - 1].length - 1]) { return 0; } int tmp = matrix[0].length; int count = 0; for (int i = 0; i < matrix.length; i++) { if (target > matrix[i][matrix[i].length - 1]) { continue; } for (int j = 0; j < tmp; j++) { if (matrix[i][j] == target) { count++; tmp = j; break; } } if (tmp == 0) { break; } } return count; } }