74. Search a 2D Matrix
来源:互联网 发布:房屋外观设计简单软件 编辑:程序博客网 时间:2024/06/05 06:48
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
.
这道题目主要涉及二分查找和数组的知识。关于二分查找,之前有过类似的题目,这个算法很经典,主要要注意left和right的更新(需要和判断条件对应):有以下几种情况等价:
1. if(mid<tar) right=mid-1; else left=mid;
2.if(mid=tar) return mid; else if(mid<tar) right=mid-1; else right=mid+1;
3.if(mid>tar) left=mid+1; else right=mid;
这道题因为已经对数组排好序了,所以直接先对行搜索,如果找到所在的行就在这一行二分搜索。
public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null||matrix.length==0) return false; int m = matrix.length; int n = matrix[0].length; if(n==0) return false; int i=0; while(i<m){ if(target>=matrix[i][0]&&target<=matrix[i][n-1]){ if(target==matrix[i][0]||target==matrix[i][n-1]) return true; int left = 0; int right = n-1; while(left<right){ if(target==matrix[i][left]||target==matrix[i][right]) return true; int mid = (left+right)/2; if(target>matrix[i][mid]) left = mid+1; else right = mid; } return false; } if(target<matrix[i][0]) return false; i++; } return false; }
阅读全文
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- OpenGL
- 关于Spring Boot集成MyBatis、通用Mapper、PageHelper
- linux命令生成filelist
- python面向对象基础
- 一部关于IT的电影
- 74. Search a 2D Matrix
- saltstack的常用操作(三) 命令与模块的执行
- Coordinator-wf-mr
- 获取样式的时候用offsetWidth 这类有Bug 要用 obj.currentStyle.width 或getComputedStyle(obj,null).width
- codeforce Maximum of Maximums of Minimums(区间划分 求区间最小值最大值问题)
- error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http:/
- PullToRefreshGridView
- 创建线程继承Thread和实现Runnable接口
- 链表的简单操作