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
44 changes: 44 additions & 0 deletions Problem6.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Time Complexity : O(log N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length -1;

// Use the Binary Search approach since we need to solve this in O(log N)
// Even though the array is rotated we always know that one half will be always sorted
while (left <= right) {
// Identigy the mid
int mid = left + (right - left)/2;

//return is mid is the target
if (nums[mid] == target) return mid;

//check if left half is sorted
if (nums[left] <= nums[mid]) {
//check if the left half is sorted
if (target >= nums[left] && target < nums[mid]) {
//search left half
right = mid - 1;
} else {
// search right half
left = mid + 1;
}
} else {
//check if the right half is sorted
if (target <= nums[right] && target > nums[mid]) {
//search right half
left = mid + 1;
} else {
//search left half
right = mid - 1;
}
}
}

return -1;
}
}
28 changes: 28 additions & 0 deletions Problem7.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time Complexity : O(log N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

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

return -1;
}
}
29 changes: 29 additions & 0 deletions Problem8.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// 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

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 r = mid / n;
int c = mid % n;

if (matrix[r][c] == target) return true;

if (matrix[r][c] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}