diff --git a/SearchInRotatedArray.java b/SearchInRotatedArray.java new file mode 100644 index 00000000..0f83c7eb --- /dev/null +++ b/SearchInRotatedArray.java @@ -0,0 +1,41 @@ +// 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 + + +// Your code here along with comments explaining your approach in three sentences only +// 1: For a rotated sorted array, at least either left or right half of the array will be sorted +// 2: We use this property to determine which pointers to move to find the target +// 3: For a left sorted array, we move the high pointer closer, for a right sorted array, we move the low pointer closer +class Solution { + public int search(int[] nums, int target) { + int low = 0; + int high = nums.length - 1; + + while(low <= high){ + int mid = low + ((high-low)/2); + if(nums[mid] == target){ + return mid; + } + 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[high] >= target && nums[mid] < target){ + low = mid + 1; + } + else + high = mid - 1; + } + }; + return -1; + } +} \ No newline at end of file diff --git a/SearchInUnknownArray.java b/SearchInUnknownArray.java new file mode 100644 index 00000000..1aa10e79 --- /dev/null +++ b/SearchInUnknownArray.java @@ -0,0 +1,35 @@ +// Time Complexity : O(log n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : No - premium question +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach in three sentences only +// 1: We set a fixed range to search within and then use ArrayReader to double the range in which we're searching +// 2: We use the ArrayReader to get the mid element +// 3: And use Binary Search as normal to find the target element +class Solution{ + public int search(ArrayReader reader, int target){ + int low = 0; + int 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; + } +} \ No newline at end of file