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

Search a 2D Matrix -- leetcode

时间:2015-04-12 13:27:51      阅读:98      评论: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.



基本思路:

1. 先用折半查找,定位到行。

2. 再用折半查找,定位到列。

这里用到的是二段式,二分法查找, 即循环中,只有2个分支,省掉 判等的分支。

在第一次二分退出循环后,需要判断,待查找值,位于当前行前,或者是前一行。


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

        const int row = low && matrix[low][0] > target ? low - 1: low;
        low = 0, high = matrix[row].size()-1;
        while (low < high) {
            const int mid = low + (high - low) / 2;
            if (matrix[row][mid] < target)
                low = mid + 1;
            else
                high = mid;
        }
        
        return matrix[row][low] == target;
    }
};


此题可以把二维数组,当成一个一维有序数组进行折半查找。

但需要一个将一维坐标,转换成二维坐标的过程。 将需要额外进/和%的运算。

Search a 2D Matrix -- leetcode

标签:leetcode   面试   二分法   二维数组   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45008787

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