剑指Offer面试题3 & Leetcode74
来源:互联网 发布:幼儿美工环境创设方案 编辑:程序博客网 时间:2024/05/18 09:02
剑指Offer面试题3 & Leetcode74
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.
解题思路
考虑:如果数组中的数小于target,那么我们将会继续在该数右方和下方寻找target;如果数组中的数大于target,那么我们将会继续在该数左方和上方寻找target,这两种可能都会导致继续寻找的区域出现重叠。
如果我们从数组右上角开始比较,就可以排除掉一个区域,不会出现重复,例如,如果该数小于target,因为该行中次数最大,所以只会去它下方继续寻找target。
Solution
public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0) return false; int row = 0; int column = matrix[0].length-1; while(row<matrix.length && column >=0){ if(matrix[row][column] == target) return true; else if(matrix[row][column] > target){ column--; }else{ row++; } } return false; }
0 0
- 剑指Offer面试题3 & Leetcode74
- 剑指offer面试题3
- 《剑指offer》面试题3
- 剑指offer 面试题3
- 剑指offer面试题3
- 【面试题】剑指offer 3
- 剑指offer 面试题3
- 剑指offer 面试题
- 剑指offer面试题
- 读书笔记-剑指offer 面试题3
- 《剑指offer》面试题3(2)
- 剑指Offer(面试题3~5)
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- 剑指offer面试题08
- 剑指offer面试题42
- FFmpeg学习1:视频解码
- 前端开发100元/页,空心科技切入IT人才共享
- python pip list
- Github之Fork
- LeetCode12. Integer to Roman
- 剑指Offer面试题3 & Leetcode74
- 前端生产环境搭建-centos(未完)
- cannot find #include "caffe/proto/caffe.pb.h"
- 工厂模式与抽象工厂在实际项目中的应用
- Kafka入门经典教程
- centos7安装中文字体
- Python 3基础教程16-类
- Java集合不能存放基本数据类型,只存放对象的引用
- Java Web学习笔记