leetcode_Search a 2D Matrix II

来源:互联网 发布:十分钟学会python 编辑:程序博客网 时间:2024/05/21 06:43

描述:

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[  [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]]

Given target = 5, return true.

Given target = 20, return false.

思路:

本题有两种思路,首先想到的是对该矩阵的每一行做二分查找,后来跟人探讨时才知道还有另外一种O(n)时间复杂的方法,下面就细说下这个O(n)时间复杂度的方法

1.首先从第一行的最后一个开始,假设该值为x,当x大于target的时候,那target肯定小于该列的其它值,因为该列是递增的,colNum--;

2.同理,如果target大于x的时候,说明target大于该行的其它值,因为改行也是递增的,即rowNum++;

3.由于每次以一行的速度来排除,所以O(n)的时间复杂度既可以解决该问题。

代码:

O(nlogn)的方法,对每一行进行二分查找

public boolean searchMatrix(int[][] matrix, int target) {        if(matrix==null)            return false;        int endIndex=0;        if(matrix[matrix.length-1][matrix[0].length-1]<target)//判断最大的是否小于target            return false;        for(int i=0;i<matrix.length;i++)//判断要查找的范围        {            if(matrix[i][0]>target)            {                endIndex=i;                break;            }        }        if(matrix[matrix.length-1][0]<=target)            endIndex=matrix.length;        for(int i=0;i<endIndex;i++)//对每一维应用二分查找        {            if(binarySearch(matrix[i],target))                return true;        }        return false;    }    public boolean binarySearch(int []arr,int target)//二分查找    {        int start=0,end=arr.length-1,mid=0;        while(start<=end)        {            mid=(start+end)/2;            if(arr[mid]==target)                return true;            else if(arr[mid]>target)                end=mid-1;            else                start=mid+1;        }        return false;    }

O(N)时间复杂度的解法

public boolean searchMatrix(int[][] matrix, int target) {        if(matrix==null)            return false;        int endIndex=matrix.length;        int rowNum=0,columNum=matrix[0].length-1;        while(rowNum<endIndex&&columNum>=0)        {            if(matrix[rowNum][columNum]==target)                return true;            else if(matrix[rowNum][columNum]<target)                rowNum++;            else if(matrix[rowNum][columNum]>target)                columNum--;        }        return false;    }


0 0
原创粉丝点击