LeetCode 74th title: Search two-dimensional matrix (medium)

LeetCode 74th title: Search two-dimensional matrix (medium)

  • Title: prepared by an efficient algorithm to determine the mxn matrix, the presence or absence of a target value. This matrix has the following characteristics: an integer of from left to right in each row in ascending order. The first integer is greater than the last row of each integer previous row.

Here Insert Picture Description

  • Problem-solving ideas: the method of double-layer search pointer.
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int D = matrix.length;
        if(D==0) return false;
        int R = matrix[0].length-1;
        if(R==-1) return false;
        for(int i=0;i<D;i++){
            if(target>=matrix[i][0] && target<=matrix[i][R]){
                int left = 0;
                while(left<=R){
                    if(target==matrix[i][left] || target==matrix[i][R]) return true;
                    
                    if(target>matrix[i][R] || target<matrix[i][left]) return false;     
                    R--;
                    left++;
                }
            }else if(target<matrix[i][0]){
                return false;
            }
        }
        return false;
    }
}

Here Insert Picture Description

  • Problem solution approach: imagine one-dimensional array, the method of dichotomy.
class Solution {
  public boolean searchMatrix(int[][] matrix, int target) {
    int m = matrix.length;
    if (m == 0) return false;
    int n = matrix[0].length;

    // 二分查找
    int left = 0, right = m * n - 1;
    int pivotIdx, pivotElement;
    while (left <= right) {
      pivotIdx = (left + right) / 2;
      pivotElement = matrix[pivotIdx / n][pivotIdx % n];
      if (target == pivotElement) return true;
      else {
        if (target < pivotElement) right = pivotIdx - 1;
        else left = pivotIdx + 1;
      }
    }
    return false;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Here Insert Picture Description

Published 79 original articles · won praise 7 · views 1357

Guess you like

Origin blog.csdn.net/new_whiter/article/details/104516592