Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0;
int r = size(nums);
while (l < r) {
int m = l + (r - l) / 2;
if (nums[m] >= nums[l]) { // 左侧升序
if (nums[l] > nums[r - 1]) { // 位于右侧
l = m + 1;
} else { // 位于左侧
return nums[l];
}
} else { // 左侧不为升序则右侧一定为升序
if (m > 0 && nums[m] > nums[m - 1]) { // 位于左侧
r = m;
} else { // 位于右侧
return nums[m];
}
}
}
return INT_MAX;
}
};
class Solution {
public:
int findMin(vector<int>& nums) {
auto it = upper_bound(begin(nums) + 1, end(nums), nums[0], greater<int>{});
return it == end(nums) ? nums[0] : *it;
}
};
class Solution {
public:
int findMin(vector<int>& nums) {
int l = 1;
int r = size(nums);
while (l < r) {
int m = l + (r - l) / 2;
if (nums[m] < nums[0]) {
r = m;
} else {
l = m + 1;
}
}
return l != size(nums) ? nums[l] : nums[0];
}
};