Leetcode the dichotomy thematic -240 search a two-dimensional matrix II (Search a 2D Matrix II)

Leetcode the dichotomy thematic -240 search a two-dimensional matrix II (Search a 2D Matrix II)


 

Prepared by an efficient algorithm to search  m  X  n-  matrix of a matrix target value target. This matrix has the following characteristics:

  • Elements of each row in ascending order from left to right.
  • Element of each column from top to bottom in ascending order.

Example:

Existing matrix multiplied as follows:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

= A given target  5, returns  true.

= A given target  20, returns  false.


 

Find the target in the two-dimensional matrix, that since this dichotomy topic in question, we do with the dichotomy.

Take out each line, divided by two, found a return to true, you can not find the search for the next line.

 

AC Code:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0 || matrix==null) return false;
        
        for(int i=0;i<matrix.length;i++){
            int[] temp = matrix[i];
            if(temp.length==0 || temp==null) return false;
            if(binarySearch(temp,0,temp.length-1,target)){
                return true;
            }
        }
        return false;
    }

    private boolean binarySearch(int[] nums, int L, int R, int target) {
        
        while(L<R){
            int mid = (L+R)>>>1;
            if(nums[mid]==target){
                return true;
            }else if(nums[mid]>target){
                R = mid-1;
            }else{
                L = mid+1;
            }
        }
        if(nums[L]==target) return true;
        
        return false;
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11410210.html