題目:在一個二維數組中,每一行都按照從左到右遞增的順序,每一列都按照從上到下的遞增順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷該整數是否在數組中。 舉例: 0 1 2 5 2 3 4 7 4 4 4 8 5 7 7 9 首先選取右上角的數字, 若該數字等于要查找的數字,查找過程結束; 若該數字大于要查找的數字,則往左繼續查找; 若該數字小于要查找的數字,則往下繼續查找。
java代碼實現如下:
public class Finder { //m行n列,要查找的數字為x public boolean findX(int[][] mat, int m, int n, int x) { if (mat == null && mat.length == 0) return false; int row = 0; int col = n - 1; while(row < m && col >= 0){ if(mat[row][col] == x){ return true; } else if(mat[row][col] < x){ row++; } else{ col--; } } return false; }}新聞熱點
疑難解答