| 1 | class Solution { |
| 2 | public int findMin(int[] nums) { |
| 3 | |
| 4 | // If No elements are present return -1 |
| 5 | if(nums.length==0) return -1; |
| 6 | // If array is rotated N times then array remains sorted or if only one element is present |
| 7 | if(nums.length==1 || nums[0] < nums[nums.length-1]) return nums[0]; |
| 8 | // if two elements are present return minimum of the two |
| 9 | if(nums.length==2) return Math.min(nums[0], nums[1]); |
| 10 | |
| 11 | int start = 0, end = nums.length-1; |
| 12 | // binary search |
| 13 | while(start<= end) |
| 14 | { |
| 15 | int mid = start + (end-start)/2; |
| 16 | // found the element if mid element is less than mid-1 element |
| 17 | if(mid>0 && nums[mid] < nums[mid-1]) return nums[mid]; |
| 18 | // if you are inside the sorted array then move towards the unsorted array |
| 19 | else if(nums[mid] < nums[end]) end = mid-1; |
| 20 | // if you are inside the unsorted array then move towards the last element of unsorted array |
| 21 | else if(nums[mid] > nums[end]) start = mid+1; |
| 22 | |
| 23 | } |
| 24 | return -1; |
| 25 | |
| 26 | } |
| 27 | } |
nothing calls this directly
no outgoing calls
no test coverage detected