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

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

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.
[Thoughts]
做两次二分就好了,首先二分第一列,找出target所在的行,然后二分该行。
[Code]
1:       bool searchMatrix(vector
> &matrix, int target) { 2: int row = matrix.size(); 3: if(row ==0) return false; 4: int col = matrix[0].size(); 5: if(col ==0) return false; 6: if(target< matrix[0][0]) return false; 7: int start = 0, end = row-1; 8: while(start<= end) 9: { 10: int mid = (start+end)/2; 11: if(matrix[mid][0] == target) 12: return true; 13: else if(matrix[mid][0] < target) 14: start = mid+1; 15: else 16: end = mid-1; 17: } 18: int targetRow = end; 19: start =0; 20: end = col-1; 21: while(start <=end) 22: { 23: int mid = (start+end)/2; 24: if(matrix[targetRow][mid] == target) 25: return true; 26: else if(matrix[targetRow][mid] < target) 27: start = mid+1; 28: else 29: end = mid-1; 30: } 31: return false; 32: }
注意,
二分的条件应该是(start<=end), 而不是(start<end)。

转载于:https://www.cnblogs.com/codingtmd/archive/2013/03/18/5078891.html

你可能感兴趣的文章
聊聊前端国际化文案该如何处理
查看>>
JS难点之hoist
查看>>
“独角兽”企业都爱选择腾讯云,背后原因值得考究
查看>>
浅析 Vue 2.6 中的 nextTick 方法
查看>>
199. Binary Tree Right Side View
查看>>
配置SpringBoot方便的切换jar和war
查看>>
2018最佳GAN论文回顾(下)
查看>>
Vue使用element-ui所遇BUG与需求集结(二)
查看>>
弹性公网EIP,让网络更自由、灵活
查看>>
一对一直播源码都实现了哪几种常见的优化技术? ...
查看>>
Unity学习系列一简介
查看>>
利用Python框架pyxxnet_project实现的网络服务
查看>>
一个最简单的WebSocket hello world demo
查看>>
C# 8.0的三个令人兴奋的新特性
查看>>
关于ip_conntrack跟踪连接满导致网络丢包问题的分析
查看>>
烂泥:linux学习之VNC远程控制(一)
查看>>
如何解决Xshell使用时中文字体是躺倒显示的问题
查看>>
Scala函数的定义的几种写法
查看>>
【iphone应用开发】iphone 应用开发之二:UITextView控件的详细讲解
查看>>
HTML5 API摘要
查看>>