28. 搜索二维矩阵

Description

Write an efficient algorithm that searches for a value in an m x n matrix.

This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example

Consider the following matrix:

[
    [1, 3, 5, 7],
    [10, 11, 16, 20],
    [23, 30, 34, 50]
]

Given target = 3, return true.

Challenge

O(log(n) + log(m)) time

public class Solution {
    /**
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        
        int left = 0;
        int right = matrix.length-1;
        
        //找出中间的一维列表;
        while(right != -1){
            if(target >= matrix[right][0]){
                break;
            }else{
                right--;
            }
        }
        
        if(right == -1){
            return false;
        }
        int hight = matrix[right].length-1;
        int low = 0;
        while(low <= hight){
            int mid = low + (hight-low)/2;
            if(target == matrix[right][mid]){
                return true;
            }
            if(target >= matrix[right][mid]){
                low = mid+1;
            }
            
            if(target < matrix[right][mid]){
                hight = mid-1;
            }
        }
        return false;
            
    }
}
public class Solution {
    /**
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        int m=matrix.length;
        if(m==0){
            return false;
        }
        int n=matrix[0].length;
        if(n==0){
            return false;
        }
        int mn=n*m;
        int start=0,end=mn-1,mid,col,row;
        while(start+1<end){
            mid=start+(end-start)/2;
            row=mid/n;
            col=mid%n;
            if(matrix[row][col]==target){
                return true;
            }else if(matrix[row][col]>target){
                end=mid;
            }else{
                start=mid;
            }
        }
        if(matrix[start/n][start%n]==target||matrix[end/n][end%n]==target){
            return true;
        }
        return false;
    }
    
}
描述
写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

每行中的整数从左到右是排序的。
每行的第一个数大于上一行的最后一个整数。
您在真实的面试中是否遇到过这个题?  
样例
考虑下列矩阵:

[
  [1, 3, 5, 7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
给出 target = 3,返回 true

挑战
O(log(n) + log(m)) 时间复杂度
posted @ 2019-04-02 21:41  故人叹  阅读(116)  评论(0)    收藏  举报