1. 程式人生 > >面試題4:二維數組中的查找

面試題4:二維數組中的查找

scrip turn all new cnblogs find auth ring 二維

在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。

請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。

package Chapter2_jichuzhishi;

/**
 * @Title: 二維數組中的查找
 * @Description:
 * @Author: Allen
 */
public class Main01 {
    public static void main(String[] args) {
        int[][] arr = {{1,2,8,9},
                {2,4,9,12},
                {
4,7,10,13}, {6,8,11,15}}; int num=7; int rows=4; int cols=4; Solution slt = new Solution(); boolean bool= slt.findNum(arr, num, rows, cols); System.out.println(bool); } } class Solution{ public boolean findNum(int[][] arr, int num, int
rows, int cols){ int row=0, col=cols-1; /*while(num!=arr[row][col]){ if(num > arr[row][col]){ row++; if(row >= rows){ return false; } } if(num < arr[row][col]){ col--; if(col < 0){ return false; } } } return true;
*/ boolean bool=false; /** * 把邊界條件的判斷放到while的判斷條件中 */ while(row < rows && col >=0){ if(arr[row][col] == num){ bool = true; break; } else if(arr[row][col] > num){ col--; }else row++; } return bool; } }

面試題4:二維數組中的查找