zoukankan      html  css  js  c++  java
  • [LeetCode] Search a 2D Matrix II

    Well, the idea is to search from the top-right element and then reduce the range for further searching by comparisons between target and the current element.

    Let's take the matrix in the problem statement as an example.

    [
      [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]
    ] 

    Suppose we want to search for 12. We first initialize r = 0 and c = 4. We compare 12 withmatrix[r][c] = matrix[0][4] = 15 and 12 < 15, so 12 cannot appear in the column of 15 since all elements below 15 are not less than 15. Thus, we decrease c by 1 and reduce the search range by a column. Now we compare 12 with matrix[r][c] = matrix[0][3] = 11 and 12 > 11, so 12 cannot appear in the row of 11 since all elements left to 11 are not greater than 11. Thus, we increase r by 1 and reduce the search range by a row. Then we reach matrix[1][3] = 12 = target and we are done (return true). If we have moved beyond the matrix and have not found the target, return false.

    Putting these together, we will have the following short codes.


    C++

     1 class Solution {
     2 public:
     3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
     4         int m = matrix.size(), n = matrix[0].size(), r = 0, c = n - 1;
     5         while (r < m && c >= 0) {
     6             if (matrix[r][c] == target) return true;
     7             if (matrix[r][c] > target) c--;
     8             else r++;
     9         }
    10         return false;
    11     } 
    12 };

    Python

     1 class Solution:
     2     # @param {integer[][]} matrix
     3     # @param {integer} target
     4     # @return {boolean}
     5     def searchMatrix(self, matrix, target):
     6         m, n, r, c = len(matrix), len(matrix[0]), 0, n - 1
     7         while r < m and c >= 0:
     8             if matrix[r][c] == target:
     9                 return True
    10             if matrix[r][c] > target:
    11                 c -= 1
    12             else: 
    13                 r += 1
    14         return False
  • 相关阅读:
    es删除索引
    真人快打11技能键位
    点到线段的距离
    行列快乐值
    按钮变色
    取数求和
    机器分配
    田忌赛马 问题
    雷达
    最小字典序
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4675650.html
Copyright © 2011-2022 走看看