您的位置:首页 > 编程语言 > Java开发

LeetCode 74(Search a 2D Matrix)Java

2016-12-01 09:33 471 查看
原题:Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties


1. Integers in each row are sorted from left to right.

2. The first integer of each row is greater than the last integer of the previous row.

给定一个m x n的矩阵,该矩阵满足如下性质:

1. 矩阵每一行的元素已经按从小到大的顺序排好序;

2. 矩阵每一行的任意一个元素都大于它上面行的任意一个元素;

思路:

面对一个在横向和纵向都是排好序的矩阵,我们不必采用依次查找的算法(复杂度O(m*n)),可以采用两次二分法,先找到对应行的索引,再在该行内进行二分查找(复杂度O(logm)*O(logn)),判断该数是否存在。

代码:

/*
Author:Jassy
Time:2016/11/30
Number:LeetCode 74
Resource:https://leetcode.com/problems/search-a-2d-matrix/
Result:AC
Conclusion:
*/
public class Solution {
boolean flag=false;
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0){
return false;
}
int[] index=new int[matrix.length];
for(int i=0;i<index.length;i++){
index[i]=matrix[i][0];
}
int count1=binarySearch(index,target);
int count2=binarySearch(matrix[count1],target);
if(flag==true){
return true;
}else{
return false;
}
}

int binarySearch(int[] nums,int target){
int left=0;
int right=nums.length-1;
int mid=0;
while(left<=right){
mid=(left+right)/2;
if(target>nums[mid]){
left=mid+1;
}else if(target<nums[mid]){
right=mid-1;
}else{
flag=true;
return mid;
}
}
return (left+right)/2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: