p95 search two-dimensional matrix (leetcode 74)

A: problem-solving ideas

The subject is half a deformation of the title search. The key to solving this problem is to look at the two-dimensional array made one-dimensional array, and then use the dichotomous thinking constantly updated. matrix [r] [c], r = mid / n, c = mid% n. Wherein n is the number of columns of the array. Time: O (log (m * n)), Space: O (1)

Two: Complete code examples (C ++ version and the Java version)

C++:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) 
    {
        if (matrix.size() == 0 || matrix[0].size() == 0) return false;
        int m = matrix.size();
        int n = matrix[0].size();
        int low = 0, high = m * n - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2;
            int r = mid / n;
            int c = mid % n;
            if (matrix[r][c] < target) low = mid + 1;
            else if (matrix[r][c] > target) high = mid - 1;
            else return true;
        }

        return false;
    }
};

Java:

class Solution {
        public boolean searchMatrix(int[][] matrix, int target)
        {
              if(matrix==null || matrix.length==0) return false;
              if(matrix[0]==null || matrix[0].length==0) return false;
              int m=matrix.length;
              int n=matrix[0].length;
              int low=0,high=m*n-1;
              while(low<=high)
              {
                  int mid=low+(high-low)/2;
                  int r=mid/n;
                  int c=mid%n;
                  if(matrix[r][c]<target) low=mid+1;
                  else if(matrix[r][c]>target) high=mid-1;
                  else return true;
              }

              return false;
        }
    }

Guess you like

Origin www.cnblogs.com/repinkply/p/12643190.html