java
比遍历还慢的bsearch
class Solution {
public boolean bsearch(int[] nums,int target) {
int l=0;
int r=nums.length-1;
while(l<=r) {
int mid=(l+r)/2;
if(nums[mid]<target) {
System.out.println(nums[mid]+" "+target);
l=mid+1;
}
else
if(nums[mid]>target) {
System.out.println(nums[mid]+" "+target);
r=mid-1;
}
else return true;
}
return false;
}
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0)return false;
if(matrix[0].length==0) return false;
for(int i=0;i<matrix.length;i++) {
if(matrix[i][0]<=target&&matrix[i][matrix[i].length-1]>=target) {
if(bsearch(matrix[i], target)) {
return true;
}
}
}
return false;
}
}
炸裂了,java自带的binarysearch比我写的快十倍
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0)return false;
if(matrix[0].length==0) return false;
for(int i=0;i<matrix.length;i++) {
if(matrix[i][0]<=target&&matrix[i][matrix[i].length-1]>=target) {
if(Arrays.binarySearch(matrix[i], target)>=0) {
return true;
}
}
}
return false;
}
}