Leetcode No.74 Search a 2D Matrix

来源:互联网 发布:linux下etc没有inittab 编辑:程序博客网 时间:2024/05/23 05:09

Question:

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.

Solution:这题不用把它当成矩阵,把矩阵当作一个已经排序的一位数组处理就行了,再采取二分法即可。

C++ Codes:

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        int rows = matrix.size();        int cols = matrix[0].size();        int left = 0, right = cols * rows - 1;        while (left != right){            int mid = (left + right - 1) >> 1;            if (matrix[mid / cols][mid % cols] < target) <span style="white-space:pre"></span>{               <span style="white-space:pre"></span>left = mid + 1;}            else {                <span style="white-space:pre"></span>right = mid;}        }        return matrix[right / cols][right % cols] == target;    }};



0 0