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
  • 相关阅读:
    读取Excel还用POI?试试这款开源工具
    Maven optional 关键字透彻图解
    Java 8 Stream Api 中的 peek 操作
    Lombok 使用详解,简化Java编程
    C# 基础知识系列- 16 开发工具篇
    C# 基础知识系列- 15 异常处理篇
    C# 基础知识系列- 14 IO篇 流的使用
    Java Spring Cloud 实战之路-01 框架选型
    C# 基础知识系列- 14 IO篇 文件的操作
    C# 基础知识系列- 14 IO篇 文件的操作
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4675650.html
Copyright © 2011-2022 走看看