码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法

时间:2015-07-19 18:10:16      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.

For example,

Consider the following matrix:

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

Given target = 3, return true.

思路:此题还是比较简单的,主要是用两个二分法,才对第一列使用,再对特定的行使用。

具体代码如下:

public class Solution {
    public boolean searchMatrix(int[][] m, int target) {
        //两个二分搜索
        //先搜索第一列,找到确定的行,然后再搜索行
        int i = 0;
        int j = m.length-1;
        int mid = 0;
        //搜寻第一列
        while(i <= j){
            mid = (i + j)/2;
            if(m[mid][0] == target){
                return true;
            }else if(m[mid][0] < target){
                i = mid + 1;
            }else{
                j = mid - 1;
            }
        }
        if(m[mid][0] > target){
            if(mid == 0){
                return false;
            }
            mid--;//mid-1
        }
        //搜寻mid行
        i = 0;
        j = m[0].length -1;
        int k = mid;
        //搜寻到了返回true
        while(i <= j){
            mid = (i + j)/2;
            if(m[k][mid] == target){
                return true;
            }else if(m[k][mid] < target){
                i = mid + 1;
            }else{
                j = mid - 1;
            }
        }
        //没有搜寻到,返回false
        return false;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法

标签:leetcode

原文地址:http://blog.csdn.net/xygy8860/article/details/46955827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!