[LeetCode]74. Search a 2D Matrix
2016-03-13 12:00
417 查看
Total Accepted: 73109 Total
Submissions: 218887 Difficulty: Medium
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:
Given target =
return
思路:
先判断是不是小于最小值,大于最大值,如果不是
从右上角开始搜索,如果小于改行最右边的值,则在改行上进行二分查找;
否则,跳过此行,在下一行进行相同操作
Submissions: 218887 Difficulty: Medium
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.
思路:
先判断是不是小于最小值,大于最大值,如果不是
从右上角开始搜索,如果小于改行最右边的值,则在改行上进行二分查找;
否则,跳过此行,在下一行进行相同操作
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(target < matrix[0][0]||target > matrix[matrix.length-1][matrix[0].length-1]) return false; boolean res = false; boolean temp = false; for (int i = 0;i < matrix.length; i++) { if (target <= matrix[i][matrix[0].length-1]){ temp = searchRange(matrix[i], target); if (temp == true) { res = true; break; } } } return res; } public boolean searchRange(int[] nums, int target) { int low = 0; int high = nums.length-1; int mid = 0; boolean r = false; while(low <= high) { mid = (low + high)/2; if (nums[mid] == target) { r = true; break; } else if (nums[mid] < target) low = mid+1; else high = mid -1; } //System.out.println(r); return r; } }
相关文章推荐
- Android学习_ContentProvider和Uri
- 第一个小应用:图片浏览器 之 三 学会使用内部存储
- 大学毕业4年-未来展望-序
- 大学毕业4年-未来展望-序
- 交换机和路由器的区别
- 大学毕业4年-未来展望-序
- Android ScrollView嵌套ViewPager滑动失效和无法正常滑动冲突问题解决方案
- HDOJ-1233 还是畅通工程(最小生成树)
- Leetcode:58. Length of Last Word(JAVA)
- caffe支持pycaffe的安装:ImportError: No module named google.protobuf.internal
- 关于Android的Build类——获取Android手机设备各种信息
- Linux内核分析——跟踪分析Linux内核的启动过程
- 欢迎使用CSDN-markdown编辑器
- 函数atof的功能及使用
- Codeforces Round #345 (Div. 2) B. Beautiful Paintings
- 第3周-项目3(3)-输出星号图
- source insight使用技巧
- 第三周项目1:个人所得税计算器
- 计算机图形学作业——DDA算法实现
- 68. Text Justification *HARD*