diff --git a/LC33.java b/LC33.java new file mode 100644 index 00000000..511f1f9c --- /dev/null +++ b/LC33.java @@ -0,0 +1,43 @@ +// Time Complexity : O(logN) +// Space Complexity : O(1) + + +// Your code here along with comments explaining your approach +//Create pointers low and high and calculate mid +//check if the left side is sorted or the right side at this point. +//if the left side is sorted, check if the target value lies in that window. If not, move the low pointer to mid+1. +// same for the right side +// return the mid element if target is found +// else return -1 if while loop exits without finding the target value. + +class Solution { + public int search(int[] nums, int target) { + //1 + int low = 0; + int high = nums.length - 1; + + //2 + while(low <= high){ + int mid = low + (high - low)/2; + + //3 + if(nums[mid] == target){ + return mid; + } else if(nums[mid] >= nums[low]){ + if(target >= nums[low] && target < nums[mid]){ + high = mid - 1; + } else { + low = mid + 1; + } + } else{ + if(target > nums[mid] && target <= nums[high]){ + low = mid + 1; + } else{ + high = mid - 1; + } + } + } + //4 + return -1; + } +} \ No newline at end of file diff --git a/LC702.java b/LC702.java new file mode 100644 index 00000000..b9cbdb4a --- /dev/null +++ b/LC702.java @@ -0,0 +1,42 @@ +// Time Complexity : O(logN) +// Space Complexity : O(1) + + + +// Your code here along with comments explaining your approach +//Create pointers low, high and calculate mid +//keep updating value of high until you get Integer.MAX_VALUE because that means you have hit array out of bound +//create a separate function specifically for binary search and use it to return the value in the search method. + + +class Solution { + public int search(ArrayReader reader, int target) { + int low = 0; + int high = 1; + + while(reader.get(high) != Integer.MAX_VALUE){ + high = high*2; + } + + return binarySearch(reader, low, high, target); + + } + + private int binarySearch(ArrayReader reader, int low, int high, int target){ + 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