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 分钟前
深入解析内存中的整数与浮点数存储
c语言·经验分享·笔记·visualstudio
Yupureki27 分钟前
从零开始的C++学习生活 9:stack_queue的入门使用和模板进阶
c语言·数据结构·c++·学习·visual studio
远远远远子28 分钟前
C++-- 内存管理
c++·算法
sprintzer44 分钟前
10.6-10.15力扣模拟刷题
算法·leetcode·职场和发展
徐子童1 小时前
算法---队列+宽搜
算法··队列·层序遍历
一念&1 小时前
每日一个C语言知识:C 数组
c语言·开发语言·算法
小年糕是糕手1 小时前
【数据结构】单链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表
疯狂吧小飞牛1 小时前
Lua C API 中的 lua_rawseti 与 lua_rawgeti 介绍
c语言·开发语言·lua
咸鱼爱学习2 小时前
【题解】B2613【深基1.习5】打字速度
数据结构·c++·算法
一匹电信狗2 小时前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio