像题中的例子我可以将其转化为:

position: 0 1 2 3 4 5 6 7 8 9 10 11

values: 1 3 5 7 10 11 16 20 23 30 34 50

row: 0 0 0 01 1 1 12 2 2 2

column: 0123 0 123012 3

其中:行数rows=3,列数columns=4

如上,这个就是将2D矩阵转化成1行数组的对应表。所以对于二分查找法的初始值为:low=0,high=rows*columns-1(总共数值的个数,因为从0开始所以减1)。而为了能够方便在given 2D matrix找到需要比对的值,我们还是需要确定行数和列数,通过上表可以看出,行数是position/columns,而列数是position%columns, 这样一来,就能很容易的在原矩阵中定位到所需要的值。剩下其他的解题思路,就与二分查找法一模一样了。

时间复杂度O(log(rows*columns))

class Solution {
public:
    /*
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    bool searchMatrix(vector<vector<int>> matrix, int target) {
        // write your code here
        int row = matrix.size();
        if (row == 0) {
            return false;
        }
        int col = matrix[0].size();
        if (col == 0) {
            return false;
        }

        int start = 0;
        int end = row * col - 1;

        while (start + 1 < end) {
            int mid = (end - start) / 2 + start;
            int x = mid / col;
            int y = mid % col;
            if (matrix[x][y] == target) {
                return true;
            } else if (matrix[x][y] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }

        int start_x = start / col;
        int start_y = start % col;

        if (matrix[start_x][start_y] == target) {
            return true;
        }

        int end_x = end / col;
        int end_y = end % col;

        if (matrix[end_x][end_y] == target) {
            return true;
        } 

        return false;
    }
};

results matching ""

    No results matching ""