searching in 2d array as O(n) with unsorted rows

后端 未结 3 1548
暖寄归人
暖寄归人 2021-01-19 11:54

I need to write a method that takes 2d array \'int [][] m\' and a value \'val\' and check if val is in the array in the complexity of O(n) while n defined as the num

3条回答
  •  佛祖请我去吃肉
    2021-01-19 12:07

    Smth. like that. In case of Every number at row i is equals or smaller then every number on row i+1, than you can check only first element in each row to define a row, where required value could be. Element in unsorted row can be found only with full scan.

    This algorithm have to scan 2 full rows only, which is O(n) where n - number of rows.

    public static boolean findValTest(int[][] m, int val) {
        for (int row = 0; row < m.length; row++) {
            if (m[row][0] <= val && row != m.length - 1)
                continue;
    
            int r = row;
    
            while (r >= row - 1 && r >= 0) {
                for (int col = 0; col < m[r].length; col++)
                    if (m[r][col] == val)
                        return true;
    
                r--;
            }
    
            return false;
        }
    
        return false;
    }
    

    Test cases:

    System.out.println(findValTest(arr3, -1)); // false
    System.out.println(findValTest(arr3, 5)); // true
    System.out.println(findValTest(arr3, 7)); // true
    System.out.println(findValTest(arr3, 55)); // false
    System.out.println(findValTest(arr3, 47)); // true
    System.out.println(findValTest(arr3, 147)); // true
    System.out.println(findValTest(arr3, 200)); // false
    System.out.println(findValTest(new int[][] { { 3, 4, 5 } }, 4));   // true
    

提交回复
热议问题