diff --git a/Problem6.java b/Problem6.java new file mode 100644 index 00000000..89dba70f --- /dev/null +++ b/Problem6.java @@ -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; + } +} \ No newline at end of file diff --git a/Problem7.java b/Problem7.java new file mode 100644 index 00000000..711b8db9 --- /dev/null +++ b/Problem7.java @@ -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; + } +} \ No newline at end of file diff --git a/Problem8.java b/Problem8.java new file mode 100644 index 00000000..c66a0279 --- /dev/null +++ b/Problem8.java @@ -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; + } +} \ No newline at end of file