Wins the offer-001- dimensional array lookup

 

topic:

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Knowledge:
two-dimensional array, Find

 

1 idea:

Using the properties: a two-dimensional matrix from left to right, top to bottom value increments.

1) on the right (or lower left) Find the angle, the upper right corner is the maximum element in the row, the column of the minimum value.

If the target value is less than the upper right corner elements, delete elements where the upper right corner of the column; if the element is greater than the upper-right corner, (then target certainly not in the upper right corner of the element where the line) delete the top right corner of the row; if equal return true.

Termination condition 2) + circulating loop variable changes from time to time, while loop written.

3) detecting a two-dimensional input array is empty, the detection target is less than the minimum array / array is greater than the maximum value, can improve the process efficiency.

Time complexity: O (col + row)

Code:

public class Solution {
    public boolean Find(int target, int [][] array) {
        int row = array.length;
        int col = array[0].length;
        
        // check if 2D Array is empty
        if (array.length == 0 || array[0].length == 0) {
            return false;
        }
 
        if (target < array[0][0] || target > array[row - 1][col - 1]) {
            return false;
        }
        // start from right-up corner
        int curRow = 0;
        int curCol = col - 1;
        while(curRow < row && curCol >= 0) {
            if(target < array[curRow][curCol]) {
                curCol--;
            } else if (target > array[curRow][curCol]) {
                curRow++;
            } else {
                return true;
            }
        }
        return false;
    }
}

 

2 ideas:

Binary search

time complexity:

O (nlogn)

One-dimensional array of two-dimensional lookup time complexity of O (logn)

Guess you like

Origin www.cnblogs.com/zyrJessie/p/12549904.html