Skip to content
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
33 changes: 33 additions & 0 deletions SearchinRotatedSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
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;
}

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

return -1;
}
}
28 changes: 28 additions & 0 deletions search2DMatrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
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 row= mid/n;
int col= mid%n;

int num= matrix[row][col];

if(num==target){
return true;
}
if(num > target){
high=mid-1;
}else{
low=mid+1;
}

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

while(reader.get(high) < target){
low = high ;
high = high * 2;
}

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;
}
}
if(reader.get(low) == target) return low;
return -1;
}
}