LeetCode 0240 -- 搜索二維矩陣II

搜索二維矩陣

題目描述

編寫一個高效的算法來搜索 m x n 矩陣 matrix 中的一個目標值 target。該矩陣具有以下特性:

每行的元素從左到右升序排列。
每列的元素從上到下升序排列。

示例:

現有矩陣 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

給定 target = 5,返回 true

給定 target = 20,返回 false

解題思路

個人AC

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;
        if (row == 0) return false;
        int col = matrix[0].length;
        if (col == 0) return false;

        // 取右上角或左下角爲“中”點
        // 以右上角元素爲例:左方元素都比它小,右方元素都比它大,類二分查找
        int i = 0, j = col - 1;
        while (i < row && 0 <= j) {
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] > target) {
                j--;
            } else {
                i++;
            }
        } 
        return false;
    }
}

時間複雜度: O(m+n)O(m + n)

空間複雜度: O(1)O(1)

最優解

同上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章