diff --git a/SearchInInfiniteSortedArray.java b/SearchInInfiniteSortedArray.java new file mode 100644 index 00000000..bae0cf39 --- /dev/null +++ b/SearchInInfiniteSortedArray.java @@ -0,0 +1,32 @@ +// Time Complexity :search: O(log n) , in Binary search we're eliminating the half of the input +// Space Complexity :0(1) +// Did this code successfully run on Leetcode : don't have leetcode premium +// Any problem you faced while coding this : couldnt run, debug and see + + +class SearchInInfiniteSortedArray { + public int search(ArrayReader reader, int target) { + int low = 0; + int high = 1; + + while(reader.get(high)target){ + high = mid-1; + } else{ + low = mid+1; + } + + } + + return -1; + + } +} diff --git a/SearchInRotatedSortedArray.java b/SearchInRotatedSortedArray.java new file mode 100644 index 00000000..7de3db22 --- /dev/null +++ b/SearchInRotatedSortedArray.java @@ -0,0 +1,50 @@ +// Time Complexity :search: O(log n) , in Binary search we're eliminating the half of the input +// Space Complexity :0(1) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : nothing + +class SearchInRotatedSortedArray { + + public int search(int[] nums, int target) { + int n = nums.length; + int low = 0; + int high = n-1; + + while(low<=high){ + int mid=low+(high-low)/2; + + if(nums[mid]==target){ + return mid; + } else if(nums[low]<=nums[mid]){ // left sorted array + if(nums[low]<=target && nums[mid]>target){ + high = mid-1; + } else{ + low = mid +1; + } + } else { + if(nums[mid] =target ){ + low = mid+1; + } else { + high = mid-1; + } + } + } + + return - 1; + + } + + public static void main(String args[]) { + SearchInRotatedSortedArray array = new SearchInRotatedSortedArray(); + int[] nums = new int[5]; + nums[0]= 5; + nums[1]=6; + nums[2]=1; + nums[3]=2; + nums[4]=4; + + + System.out.println("index of the target is " +array.search(nums, 6)); + + } +} diff --git a/TwoDMatrix.java b/TwoDMatrix.java new file mode 100644 index 00000000..ec28fbdd --- /dev/null +++ b/TwoDMatrix.java @@ -0,0 +1,44 @@ +// Time Complexity :search: O(log (m*n)) +// Space Complexity :0(1) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : nothing + +public class TwoDMatrix { + 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; + //finding the position MID in 2d array + int r=mid/n; + int c=mid%n; + + if(matrix[r][c] == target){ + return true; + } else if(matrix[r][c] > target){ + high = mid-1; + }else{ + low = mid +1; + } + } + + return false; + + } + + public static void main(String args[]) { + TwoDMatrix array = new TwoDMatrix(); + int[][] nums = new int[4][4]; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + nums[i][j] = i * 4 + j; + } + } + + + System.out.println("search returned " +array.searchMatrix(nums, 6)); + + } +}