diff --git a/findMin.java b/findMin.java new file mode 100644 index 00000000..83d9a019 --- /dev/null +++ b/findMin.java @@ -0,0 +1,29 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +class Solution { + public int findMin(int[] nums) { + int n = nums.length; + int l = 0, h = n-1; + + while(l <= h){ + if(nums[l] <= nums[h]){ + return nums[l]; + } + + int mid = l + (h - l) / 2; + if ((mid == 0 || nums[mid] < nums[mid - 1]) && (mid == n-1 || nums[mid] < nums[mid + 1])){ + return nums[mid]; + } + else if(nums[l] <= nums[mid]){ + l = mid + 1; + }else{ + h = mid - 1; + } + } + + return -1; + } +} \ No newline at end of file diff --git a/infiniteArray.java b/infiniteArray.java new file mode 100644 index 00000000..0f6e6a86 --- /dev/null +++ b/infiniteArray.java @@ -0,0 +1,33 @@ +// Time Complexity : O(logn) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : I don't know, I guess I'll have to buy leetcode premium at some point +// Any problem you faced while coding this : No +class Solution { + public static int infiniteArray(int[] nums, int target) { + int start = 0; + int end = 1; + + while (target > nums[end]) { + int newStart = end + 1; + end = end + (end - start + 1) *2; + + start = newStart; + } + return binarySearch(nums, target, start, end); + } + + static int binarySearch(int arr[], int target, int start, int end) { + while (start <= end) { + int mid = start + (end - start) / 2; + + if (target < arr[mid]) { + end = mid - 1; + } else if (target > arr[mid]) { + start = mid + 1; + } else { + return mid; + } + } + return -1; + } +} \ No newline at end of file diff --git a/searchMatrix.java b/searchMatrix.java new file mode 100644 index 00000000..f93012cc --- /dev/null +++ b/searchMatrix.java @@ -0,0 +1,34 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : Came up with this solution before the class, does not follow instructors O(logmn) solution +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + for (int i = 0; i < matrix.length; i++) { + if (binarySearch(matrix[i], target) == true) { + return true; + } + } + + return false; + } + + public boolean binarySearch(int[] n, int target) { + int left = 0; + int right = n.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (n[mid] == target) { + return true; + } else if (n[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + + } + return false; + } +} \ No newline at end of file