博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode 62] 74 Search a 2D Matrix
阅读量:5164 次
发布时间:2019-06-13

本文共 2012 字,大约阅读时间需要 6 分钟。

Problem:

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.

 

Analysis:

Since each row of the given matrix is sorted, we can use binary search to accelarate the search.

To locate the which to use binary search, we need to find 2 rows that row1's first element is less than target and row2's first element is greater then target. Then apply binary search to row1.

A problem here is the last row will never be searched, so we need to binary search it at last.

 

Code:

1 class Solution { 2 public: 3     bool searchMatrix(vector
> &matrix, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (matrix.size() == 0) { 7 return false; 8 } else if (matrix.size() == 1) { 9 return bs(matrix[0], target);10 } else {11 for (int i=1; i
target && matrix[i-1][0] < target)15 return bs(matrix[i-1], target);16 }17 18 return bs(matrix[matrix.size()-1], target);19 }20 }21 22 bool bs(vector
&array, int target) {23 int lo = 0, hi = array.size()-1;24 25 while (lo <= hi) {26 int mid = (lo+hi) / 2;27 28 if (array[mid] == target) {29 return true;30 } else if (array[mid] > target) {31 hi = mid - 1;32 } else {33 lo = mid + 1;34 }35 }36 37 return false;38 }39 };
View Code

 

转载于:https://www.cnblogs.com/freeneng/archive/2013/05/26/3099956.html

你可能感兴趣的文章
深入理解 JavaScript 事件循环(一)— event loop
查看>>
Hive(7)-基本查询语句
查看>>
注意java的对象引用
查看>>
C++ 面向对象 类成员函数this指针
查看>>
NSPredicate的使用,超级强大
查看>>
自动分割mp3等音频视频文件的脚本
查看>>
判断字符串是否为空的注意事项
查看>>
布兰诗歌
查看>>
js编码
查看>>
Pycharm Error loading package list:Status: 403错误解决方法
查看>>
steps/train_sat.sh
查看>>
转:Linux设备树(Device Tree)机制
查看>>
iOS 组件化
查看>>
(转)Tomcat 8 安装和配置、优化
查看>>
(转)Linxu磁盘体系知识介绍及磁盘介绍
查看>>
tkinter布局
查看>>
命令ord
查看>>
Sharepoint 2013搜索服务配置总结(实战)
查看>>
博客盈利请先考虑这七点
查看>>
使用 XMLBeans 进行编程
查看>>