Finding in Sword Finger Offer 01-Two-Dimensional Array

Posted by kirtan007 on Wed, 31 Jul 2019 05:45:03 +0200

Finding in Two-Dimensional Array

Time limit: 1 second
Space limitation: 32768K
Knowledge Points: Finding Arrays
Title Description:

In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in the order of increasing from left to right, and each column is sorted in the order of increasing from top to bottom. Please complete a function, input such a two-dimensional array and an integer, to determine whether the array contains the integer.
(Let row number m and column number n)

Answer 1:

/**
*Violent Solution O(n)=m*n
*Double loop traversal array
*/
public class Solution {
    public boolean Find(int target, int [][] array) {
        for(int i=0; i<array.length; i++){
            for(int j=0; j<array[i].length; j++){
                if(target == array[i][j]){
                    return true;
                }
            }
        }
        return false;
    }
}

Answer 2:

/**
*Dichotomy O(n)=m*logn
*Because each row of the array is ordered, binary lookup is used for each row.
*/
public class Solution {
    public boolean Find(int target, int [][] array) {
        for(int i=0; i<array.length; i++){
            int low = 0;
            int high = array[i].length - 1;
            while(low <= high){
                int mid = (low + high)/2;
                if(target > array[i][mid]){
                    low = mid + 1;
                }else if(target < array[i][mid]){
                    high = mid -1;
                }else{ // Find the target
                    return true;
                }
            }
        }
        return false;
    }
}

Answer 3:

/**
*Because arrays are incremental from top to bottom, from left to right (the length of each one-dimensional array is the same)
*Select the upper right corner element or the lower left corner element as the starting point
*Take the upper right corner as an example: the initial value row = 0, col = array[0].length - 1;  
*if(target < array[row][col]) col--; //(col >= 0)
*if(target > array[row][col]) row++; //(row <= array.length - 1)
*Pay attention to the termination condition of crossing the boundary, and eventually O(n)=m+n
*/
public class Solution {
    public boolean Find(int target, int [][] array) {
        int row = 0;
        int col = array[0].length - 1;
        while(row <= array.length - 1 && col >= 0){
            if(target > array[row][col]){
                row++;
            }else if(target < array[row][col]){
                col--;
            }else{
                return true;
            }
        }
        return false;
    }
}

Topics: PHP