程序员

Leetcode - Search a 2D Matrix

2016-09-27  本文已影响0人  哈比猪

题目链接

Search a 2D Matrix

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-1 题目

Given target = 3, return true

解题思路

TODO (稍后补充)

解答代码

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty()) return false;
        int rowCnt = matrix.size();
        int colCnt = matrix[0].size();
        int numCnt = rowCnt * colCnt;
        int lineNo = rowCnt - 1;
        int colNo = colCnt - 1;
        
        while(lineNo >= 0 && colNo >= 0) {
            if (matrix[lineNo][colNo] == target) return true;
            if (matrix[lineNo][colNo] > target) {
                int curNo = (lineNo+1)*(colNo+1);
                int nextNo = curNo / 2;
                lineNo = nextNo / (colCnt+1);
                colNo = nextNo % (colCnt+1);
            }
        }
        return false;       
        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读