Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BinarySearch01 #2167

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions SearchInSortedArrayOfUnknownSize.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class SearchInSortedArrayOfUnknownSize {
public int search(ArrayReader reader, int target) {
int low=0;
int high=1;
while(reader.get(high)<target){
low=high;
high=2*high;
}
while(low <=high){
int mid=low+(high-low)/2;
if(reader.get(mid)==target){
return mid;
}
if(reader.get(mid)>target){
high=mid-1;
}else{
low=mid+1;
}

}
return -1;
}
}
21 changes: 21 additions & 0 deletions SearchMatrixWithSortedRowsAndCols.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class SearchMatrixWithSortedRowsAndCols {
public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length;
int n=matrix[0].length;
int low=0;
int high=m*n-1;
while(low<=high){
int mid=low+(high-low)/2;
int r=mid/n;
int c=mid%n;
if(matrix[r][c]==target) return true;
else if(matrix[r][c]>target){
high=mid-1;
}else{
low=mid+1;
}
}
return false;
}

}
33 changes: 33 additions & 0 deletions SearchRotatedSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//LC33
class SearchRotatedSortedArray {
public int search(int[] nums, int target) {
int low=0;
int high=nums.length-1;

if(high==0 || nums==null)
return -1;
while(low<=high){
int mid= low+(high-low)/2;

if(nums[mid]==target){
return mid;
}else{
if(nums[low]<=nums[mid]){//left half is sorted
if(nums[low]<=target && nums[mid]>target){
high=mid-1;
}else{
low=mid+1;
}
}else{
if(nums[mid]<target && nums[high]>=target){
low=mid+1;
}else{
high=mid-1;
}
}
}
}
return -1;
}

}