[LeetCode] Search a 2D Matrix

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

 

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

 

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

可以参见:http://www.leetcode.com/2010/10/searching-2d-sorted-matrix.html

非常精彩

复制代码
 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int i = 0, j = matrix[0].size() - 1;
 7         
 8         while (i < matrix.size() && j >= 0)
 9         {
10             if (target == matrix[i][j])
11                 return true;
12             else if (target < matrix[i][j])
13                 j--;
14             else
15                 i++;
16         }
17         
18         return false;
19     }
20 };
复制代码
posted @   chkkch  阅读(1781)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示