702788. Sorted and Rotated Minimum
Minimum Element in a Sorted and Rotated Array3611
Summary
Find the minimum element in an array that is sorted and then rotated. This problem involves searching for an element in a sorted array, with the twist being that the array has been rotated by some unknown number of positions.
Detailed Explanation
To solve this problem, we can start by noticing that even if the array has been rotated, it still contains all elements from the original sorted array. Therefore, our goal is to find the minimum element in this new rotation.
One way to do this is to first find the point where the array was rotated. We know that the left side of this point will be larger than any number on the right side, because if not, then they would have been swapped during the rotation. Therefore, our goal becomes finding the minimum element in either the left or right half of the array.
Here's a step-by-step breakdown:
- Initialize two pointers,
leftandright, to the start and end of the array respectively. - Compare the middle element of the array with the first and last elements.
- If the middle element is greater than both the first and last elements, then it must be in the right half of the rotated array. In this case, update the left pointer to the middle index + 1.
- Otherwise, the middle element must be in the left half of the rotated array. Update the right pointer to the middle index - 1.
- Repeat steps 2-4 until
leftandrightmeet at some point. - At this point, the minimum element will be either at
left, or one position before it.
The time complexity for this algorithm is O(log n), where n is the size of the array, because we are effectively halving the search space in each iteration. The space complexity is O(1) as we only use a few extra variables.
Optimized Solutions
Java
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
}