-
Notifications
You must be signed in to change notification settings - Fork 186
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #254 from Ratna04priya/master
LeetCode Problem: 153.Find Minimum in Rotated Sorted Array in Java
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
Leetcode/Java/153.Find Minimum_in_Rotated_Sorted_Array.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
// 153. Find Minimum in Rotated Sorted Array | ||
//Problem Link - https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ | ||
|
||
class Solution { | ||
public int findMin(int[] nums) { | ||
// If the list has just one element then return that element. | ||
if (nums.length == 1) { | ||
return nums[0]; | ||
} | ||
|
||
// initializing left and right pointers. | ||
int left = 0, right = nums.length - 1; | ||
|
||
// if the last element is greater than the first element then there is no rotation. | ||
// e.g. 1 < 2 < 3 < 4 < 5 < 7. Already sorted array. | ||
// Hence the smallest element is first element. A[0] | ||
if (nums[right] > nums[0]) { | ||
return nums[0]; | ||
} | ||
|
||
// Binary search way | ||
while (right >= left) { | ||
// Find the mid element | ||
int mid = left + (right - left) / 2; | ||
|
||
// if the mid element is greater than its next element then mid+1 element is the smallest | ||
// This point would be the point of change. From higher to lower value. | ||
if (nums[mid] > nums[mid + 1]) { | ||
return nums[mid + 1]; | ||
} | ||
|
||
// if the mid element is lesser than its previous element then mid element is the smallest | ||
if (nums[mid - 1] > nums[mid]) { | ||
return nums[mid]; | ||
} | ||
|
||
// if the mid elements value is greater than the 0th element this means | ||
// the least value is still somewhere to the right as we are still dealing with elements | ||
// greater than nums[0] | ||
if (nums[mid] > nums[0]) { | ||
left = mid + 1; | ||
} else { | ||
// if nums[0] is greater than the mid value then this means the smallest value is somewhere to | ||
// the left | ||
right = mid - 1; | ||
} | ||
} | ||
return -1; | ||
} | ||
} |