查看二維數組中是否存在某個數

查看二維數組中是否存在某個數

package array_2_3;

/**
 * 判斷二維數組中,是否包含某個數字
 * 二維數組中元素,向右和向下遞增的
 */
public class Demo_4 {
    public static void main(String[] args) {
        int array[][] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
        Boolean res = Demo_4.isIn(array, 7);
        System.out.println(res);
    }

    public static Boolean isIn(int[][] array,int key){
        boolean flag = false;
        int row = array.length;//4行
        int column = array[0].length;//4列
        int rowIndex = 0;//從第一行
        int columnIndex = row - 1;//最右上方開始搜索;
        while (rowIndex < row && columnIndex >= 0){
            if (array[rowIndex][columnIndex] == key){
                flag = true;
                break;
            }else if (array[rowIndex][columnIndex] > key){//說明右面和下面都不滿足
                columnIndex --;// 直接刪除所在列
            }else {//說明左面肯定不滿足(右面已經因爲太大不滿足了)
                rowIndex ++;//直接刪所在行
            }
        }
        return flag;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章