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
30 changes: 30 additions & 0 deletions Search2DMatrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// #74. Search a 2D Matrix
// Time Complexity : O(log(m*n))
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

public class Search2DMatrix {
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 (target > matrix[r][c]){
low = mid+1;
}else {
high = mid -1;
}
}
return false;
}
}
33 changes: 33 additions & 0 deletions SearchUnknownSizeArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// #702. Search in a Sorted Array of Unknown Size
// Time Complexity : O(log(n)): n is the length of the array
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

// interface ArrayReader {
// public int get(int index) {}
// }
public class SearchUnknownSizeArray {
public int search(ArrayReader reader, int target) {
int low = 0;
int high = 1;

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

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{
low = mid+1;
}
}
return -1;
}
}
33 changes: 33 additions & 0 deletions SearhRotatedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// #33. Search in Rotated Sorted Array
// Time Complexity : O(log(n)): n is the length of the array
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

public class SearhRotatedArray {
public int search(int[] nums, int target) {
int l = 0;
int h = nums.length -1;
int m = 0;
while(l<h){
m = l + (h - l)/2;
System.out.println(m);
if (nums[m] == target) return m;
if(nums[l] <= nums[m]){
if(target >= nums[l] && target < nums[m]){
h = m - 1;
}else{
l = m + 1;
}
}else{
if(target > nums[m] && target <= nums[h]){
l = m + 1;
}else{
h = m -1;
}
}
}
if(nums[l] == target) return l;
return -1;
}
}