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

Solution of Binary Search - 1 #2017

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
25 changes: 25 additions & 0 deletions SearchIn2DMatrix
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// This solution we discussed in class.
// Time complexity o(log m * n)
// Space complexity o(1)

class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int low = 0, high = m*n-1;

while(low<=high) {
int mid = low + (high - low) /2;
int row = mid / n , col = mid % n;

if(matrix[row][col] == target) return true;
else if(matrix[row][col] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;

}
}
27 changes: 27 additions & 0 deletions SearchInRotatedArray
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//Time complexity o(log n)
//Space complexity o(1)

class Solution {
public int search(int[] nums, int target) {
int low = 0 , 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 && target <= nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
if(nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
}
32 changes: 32 additions & 0 deletions SearchInSortedUnknownArray
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/

// Time Complexity o(log n) if there are n number of elements in unknown array.
// Space complexity o(1)

class Solution {
public int search(ArrayReader reader, int target) {
int low = 0 , 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;
else if(reader.get(mid) > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;

}
}