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 == matrixi.length
  • 1 <= n, m <= 300
  • − 1 0 9 < = m a t r i x i j < = 1 0 9 -10^9 <= matrixij <= 10^9 −109<=matrixij<=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;
}
相关推荐
旖旎夜光4 分钟前
LCR 173:在点名(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找
重生之后端学习5 分钟前
438. 找到字符串中所有字母异位词[中等]✅
开发语言·数据结构·算法·leetcode·职场和发展
渡之7 分钟前
ArduPilot LowPassFilter 深度解析
算法·无人机
ting94520008 小时前
Humalike X Hermes 深度技术剖析:单指令注入群聊社交智能的底层架构、算法与跨 IM 平台实现
人工智能·算法·架构
吴声子夜歌8 小时前
Java面试——算法
java·算法·面试
evans在进步8 小时前
LeetCode 64:最小路径和——Java 原地动态规划详解
java·leetcode·动态规划
h_a_o777oah9 小时前
【图论】Tarjan 缩点:解决有向图中环的问题
c++·算法·图论·acm·强连通分量·缩点·tarjan
Tisfy9 小时前
LeetCode 1386.安排电影院座位:哈希表+位运算
算法·leetcode·散列表·题解·哈希表
Nil2089 小时前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
M78佐菲10 小时前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法