diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..76a65232 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,31 @@ +// Time Complexity : O(log(m*n)) where m is the number of rows and n is the number of columns in the matrix +// 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 +// We are treating the 2D matrix as a 1D array and applying binary search on it. +// We calculate the mid index and then find the corresponding row and column in the matrix using the mid index. We then compare the value at that position with the target and adjust our low and high pointers accordingly until we find the target or exhaust our search space. +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length; + int n = matrix[0].length; + int total = m*n; + int low = 0; + int high = total-1; + while(low<=high){ + int mid = low + (high-low/2); + int row = mid/n; + int column = mid%n; + if(matrix[row][column] == target){ + return true; + }else if(matrix[row][column] < target){ + low = mid+1; + }else{ + high = mid-1; + } + } + return false; + + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..af9251b6 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,43 @@ +// 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 +// We are using binary search to find the target in the rotated sorted array. +// We calculate the mid index and then determine which side of the array is sorted. +// Based on the sorted side, we adjust our search range accordingly. +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]){ + if(target >= nums[low] && target <= nums[mid]){ + high = mid -1; + }else{ + low = mid +1; + } + }else{ + if(target <= nums[high] && target >= nums[mid]){ + low = mid +1; + }else{ + high = mid -1; + } + + } + //5,6,7,0,1,2,3 + + + + } + + return -1; + + + } +} \ No newline at end of file