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

Binary search 1 hw #2048

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
83 changes: 83 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,68 @@
## Problem1
Search a 2D Matrix(https://leetcode.com/problems/search-a-2d-matrix/)

class Solution {
public boolean searchMatrix(int[][] matrix, int target) {

if(matrix.length == 0) return false;
if(matrix[0][0] == target) return true;

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 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;
}
}

## Problem2
Search in a Rotated Sorted Array (https://leetcode.com/problems/search-in-rotated-sorted-array/)

class Solution {
public int search(int[] nums, int target) {

if(nums.length == 0) return -1;

int n = nums.length;
int low = 0, high = n - 1;

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

return -1;
}
}

## Problem3
Search in Infinite sorted array:
Expand All @@ -17,3 +74,29 @@ https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/

Given a sorted array of unknown length and a number to search for, return the index of the number in the array. Accessing an element out of bounds throws exception. If the number occurs multiple times, return the index of any occurrence. If it isn’t present, return -1.

public 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;
} else if(reader.get(mid) > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}

return -1;
}
}