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;
}
相关推荐
今儿敲了吗17 分钟前
算法复盘——前缀和
笔记·学习·算法
ulias21237 分钟前
智能指针简述
开发语言·c++·算法
阿昭L38 分钟前
Windows通用的C/C++工程CMakeLists
c语言·c++·windows·makefile·cmake
寻寻觅觅☆39 分钟前
东华OJ-基础题-58-素数表(C++)
开发语言·c++·算法
AI成长日志39 分钟前
【强化学习专栏】深度拆解:多智能体强化学习核心理论与工程实践
算法
Flying pigs~~40 分钟前
基于TF_IDF和Bagging的文本分类全过程
算法·随机森林·机器学习·nlp·文本分类
树獭叔叔43 分钟前
FFN 激活函数深度解析:从 ReLU 到 SwiGLU 的演进之路
算法·aigc·openai
啊我不会诶1 小时前
最小生成树
c++·笔记·学习·算法
liuyao_xianhui1 小时前
优选算法_栈_删除字符中的所有相邻重复项_C++
开发语言·数据结构·c++·python·算法·leetcode·链表
always_TT1 小时前
C语言中的布尔值:_Bool与stdbool.h
c语言·开发语言