Java中排序二维数组搜索的最佳时间复杂度

时间:2016-01-25 20:28:01

标签: java

所以我有以下代码来搜索已排序的2D数组中的目标数字,但我不确定这是否是最好的时间复杂度,就像Big-Oh而言,我读到有一种方法可以做O(N),但我不确定我的算法是否足够有效。

public class Search2DArray {

public static int search(int[][] arrayA, int number, int target) {
    int i = 0;
    int j = number - 1;
    while (i < number && j >= 0) {
        if (arrayA[i][j] == target) {
            System.out.printf("\n Found at %d, %d", i, j);
            return 1;
        }
        if (arrayA[i][j] > target) {
            j--;
        } else {
            i++;
        }
    }

    System.out.printf("\n Element not found");
    return 0;
}

public static void main(String[] args) {
    int arrayA[][] = {{1, 2, 3, 4}, 
                   {5, 6, 7, 8}, 
                   {9, 10, 11, 12}};
    search(arrayA, 3, 11);
}
}

1 个答案:

答案 0 :(得分:0)

如果您的2D数组已经排序,您可以简单地减少要选择的行并在您认为包含目标数字的行上运行二进制搜索,这可能会降低复杂性,甚至可能是LOG的顺序