(java) Search a 2D Matrix
来源:互联网 发布:哪个象棋软件好 编辑:程序博客网 时间:2024/06/16 04:26
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
.
思路,就是用二分查找先找行再找列!
代码如下(已通过leetcode)
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=findrow(matrix, target, 0, matrix.length-1);
//System.out.println("第"+row+"行");
if(findit(matrix, row, target, 0, matrix[row].length-1)==Integer.MIN_VALUE) return false;
else {
//int position=findit(matrix, row, target, 0, matrix[row].length-1);
//System.out.println("第"+row+"行"+"第"+position+"位");
return true;
}
}
public int findrow(int[][] matrix,int target,int low,int high) {
while(low<=high) {
if(matrix[low][matrix[low].length-1]<target) low++;
else {
return low;
}
}
return low-1;
}
public int findit(int[][] matrix,int row,int target,int low,int high) {
if(low>high) return Integer.MIN_VALUE;
int mid=(low+high)/2;
if(matrix[row][mid]==target) return mid;
else {
if(matrix[row][mid]>target){
high=mid-1;
} else {
low=mid+1;
}
return findit(matrix, row, target, low, high);
}
}
}
- [Leetcode] Search a 2D Matrix (Java)
- Search a 2D Matrix Java
- Search a 2D Matrix (Java)
- [LeetCode][Java] Search a 2D Matrix
- (java) Search a 2D Matrix
- leetcode:Search a 2D Matrix 【Java】
- Search a 2D Matrix leetcode java
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- 20160124.CCPP详解体系(0003天)
- 嵌入式的瑞士军刀 - BusyBox
- 栈、双链表
- You need to use a Theme.AppCompat theme (or descendant) with this activity.
- 20160125.CCPP详解体系(0004天)
- (java) Search a 2D Matrix
- css属性 知识总结
- 20160126.CCPP体系详解(0005天)
- 用c语言代码编写的游戏“简易五子棋”
- Java基础04 封装与接口
- 编程题#3:计算数列平方和(C++程序设计第10周)
- C语言的流程控制
- RXJava学习笔记(2)
- 20160127.CCPP体系详解(0006天)