阿里面試算法題-二維遞增數組的查找

阿里面試算法題-二維遞增數組的查找

注意:轉載請說明,來自轉自itboy-木小草尊重原創,尊重技術

題目:

一個n*m的二維數組,每一行從左到右依次遞增,每一列從上到下依次遞增。問:給你一個數字,如何能快速的輸出他在數組中的位置。


    /**
     * 一個n*m的二維數組,每一行從左到右依次遞增,每一列從上到下依次遞增。
     * 問:給你一個數字,如何能快速的輸出他在數組中的位置。
     */
    public static int[] getPos(int[][] a,int tag) {
        int len = a.length;
        int col = a[0].length;
        /*
         * 排除極端可能
         */
        if (a[0][0]>tag || a[len-1][col-1]<tag) {
            return new int[]{-1,-1};
        }
        for (int i = 0,j = col - 1; i < len && j >= 0;) {
            if (a[i][j] == tag) {
                return new int[]{i,j};
            }else if (a[i][j] < tag) {
                i++;
            }else {
                j--;
            }
        }
        return new int[]{-1,-1};
    }

    public static void main(String[] args) {
        int[][] a = new int[][]{{1,2,3},{2,3,4},{5,8,9},{7,10,11}};
        int[] result = getPos(a, 6);
        System.out.println(result[0] +","+ result[1]);
        result = getPos(a, 7);
        System.out.println(result[0] +","+ result[1]);
    }

時間複雜度:n+m

發佈了29 篇原創文章 · 獲贊 18 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章