LeetCode //C - 240. Search a 2D Matrix II

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.
Example 1:

Input: 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
Output: true

Example 2:

Input: 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 = 20
Output: false

Constraints:
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • − 1 0 9 < = m a t r i x [ i ] [ j ] < = 1 0 9 -10^9 <= matrix[i][j] <= 10^9 −109<=matrix[i][j]<=109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • − 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 −109<=target<=109

From: LeetCode

Link: 240. Search a 2D Matrix II


Solution:

Ideas:

To search efficiently in such a matrix, you can take advantage of its properties. Start from the top right corner of the matrix:

  1. If the target is greater than the value in the current position, you can move down because all the values in the current row to the left are smaller than the target.
  2. If the target is smaller than the value in the current position, you can move left because all the values in the current column below are larger than the target.
  3. If you find the target, return true.
  4. If you reach the bounds of the matrix (leftmost column or bottom row) without finding the target, the target does not exist in the matrix.
Code:
c 复制代码
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {
    int row = 0;
    int col = *matrixColSize - 1;
    
    while (row < matrixSize && col >= 0) {
        if (matrix[row][col] == target) {
            return true;
        } else if (matrix[row][col] > target) {
            col--;
        } else {
            row++;
        }
    }
    
    return false;
}
相关推荐
代码游侠2 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_763472462 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy3 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异3 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_706653233 小时前
分布式系统安全通信
开发语言·c++·算法
天天爱吃肉82184 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
alphaTao4 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习4 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
颜酱4 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL4 小时前
day50 单调栈
数据结构·算法·leetcode