[LeetCode] Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while(l <= r) {
int m = l + (r-l)/2;
int L = m - 1 >= 0 ? nums[m-1] : INT_MAX;
int R = m + 1 < nums.size() ? nums[m+1] : INT_MAX;
if(L >= nums[m] and nums[m] <= R) return nums[m];
else if(nums[m] < nums[r])
r = m - 1;
else l = m + 1;
}
return INT_MIN;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/23/PS/LeetCode/find-minimum-in-rotated-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.