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

Implementation for RotatedSortedArray Search 2D Matrix UnknowSizeSortedArray #1984

Open
wants to merge 1 commit 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
5 changes: 5 additions & 0 deletions ArrayReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public interface ArrayReader {
public default int get(int index) {
return Integer.MAX_VALUE;
}
}
33 changes: 33 additions & 0 deletions RotatedSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class RotatedSortedArray {

public int search(int[] nums, int target){
int low = 0;
int high = nums.length-1;
while(low < high){
int mid = low + (high - low)/2;
if(nums[mid] == target){
return mid;
}
else{
if(nums[low]<=nums[mid]){
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;

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

}
return false;
}
}
29 changes: 29 additions & 0 deletions UnknownSizeSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class UnknownSizeSortedArray {
public int search(ArrayReader reader, int target) {
int low = 0;
int high = 1;

while(low<=high){
int mid = low + (high - low)/2;
if(reader.get(mid) == target){
return mid;
}
else{
if(target < reader.get(mid)){
high = mid - 1;
}
else if(reader.get(high)>target){
low = mid + 1;
}
else {
low = high;
high = 2 * high;

}
}
}

return -1;

}
}