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;
}
相关推荐
摘星编程15 分钟前
Ascend C编程语言详解:打造高效AI算子的利器
c语言·开发语言·人工智能
自然常数e21 分钟前
深入理解指针(6)
c语言·数据结构·算法·visual studio
Xの哲學21 分钟前
Linux VxLAN深度解析: 从数据平面到内核实现的全面剖析
linux·服务器·算法·架构·边缘计算
TL滕25 分钟前
从0开始学算法——第十八天(分治算法练习)
笔记·学习·算法
一杯美式 no sugar28 分钟前
数据结构——栈
c语言·数据结构·
月明长歌38 分钟前
【码道初阶】【LeetCode 958】判定完全二叉树:警惕 BFS 中的“管中窥豹”陷阱
算法·leetcode·宽度优先
一直都在5721 小时前
数据结构入门:二叉排序树的构建与相关算法
数据结构·算法
_Minato_2 小时前
数据结构知识整理——复杂度的计算
数据结构·经验分享·笔记·算法·软考
listhi5202 小时前
针对燃油运输和车辆调度问题的蚁群算法MATLAB实现
前端·算法·matlab
月明长歌2 小时前
【码道初阶】【LeetCode 102】二叉树层序遍历:如何利用队列实现“一层一层切蛋糕”?
java·数据结构·算法·leetcode·职场和发展·队列