寫出1個高效的算法來搜索m×n矩陣中的值,返回這個值出現的次數。
這個矩陣具有以下特性:
每行中的整數從左到右是排序的。
每列的整數從上到下是排序的。
在每行或每列中沒有重復的整數。
和判斷1個數是不是在這樣的2維矩陣中1樣,判斷找到合適就結束了
這個題目有多個,找到1個的時候還要繼續找,直到找完
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 col = matrix[0].length;
int count =0;
int i=0;
int j=col-1; // 右上開始
while(i<row && j>=0){
if(matrix[i][j] > target){ // 大 列 ⑴
j--;
}else if(matrix[i][j]< target){ // 小 行+1
i++;
}else{ // 行+1 列⑴,題目說明每行或每列沒有重復數
count++;
i++;
j--;
}
}
return count;
}
}
上一篇 4.2、Android Studio壓縮你的代碼和資源
下一篇 BT是怎么下載的