LeetCode //C - 154. Find Minimum in Rotated Sorted Array II

154. Find Minimum in Rotated Sorted Array II

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

  • 4,5,6,7,0,1,4\] if it was rotated 4 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 that may contain duplicates, return the minimum element of this array.

You must decrease the overall operation steps as much as possible.

Example 1:

Input: nums = [1,3,5]
Output: 1

Example 2:

Input: nums = [2,2,2,0,1]
Output: 0

Constraints:
  • n == nums.length
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • nums is sorted and rotated between 1 and n times.

From: LeetCode

Link: 154. Find Minimum in Rotated Sorted Array II


Solution:

Ideas:

1. Initialization: Set two pointers, left and right, at the beginning and end of the array, respectively.

2. While Loop: Continue searching as long as left is less than right.

3. Middle Element: Calculate the middle position mid between left and right.

4. Decision Tree:

  • If nums[mid] is greater than nums[right], the minimum is in the right half (excluding mid), so move left to mid + 1.
  • If nums[mid] is less than nums[right], the minimum could be mid or to the left of mid, so move right to mid.
  • If nums[mid] equals nums[right], reduce right by one to gradually eliminate duplicates without skipping the minimum.

5. Conclusion: Once left equals right, the minimum element is found, as the search space is narrowed down to a single element.

Code:
c 复制代码
int findMin(int* nums, int numsSize) {
    int left = 0, right = numsSize - 1;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] > nums[right]) {
            left = mid + 1;
        } else if (nums[mid] < nums[right]) {
            right = mid;
        } else { // nums[mid] == nums[right]
            right--;
        }
    }
    return nums[left];
}
相关推荐
lvxiangyu115 小时前
MPPI 算法证明重构:基于无穷维泛函变分与 KL 散度的构造性推导
算法·重构·最优控制·随机最优控制
2301_818419015 小时前
C++中的解释器模式变体
开发语言·c++·算法
ab1515175 小时前
3.25完成*23、*24、*28、*30、*33、*38、*39、*40
算法
颜酱5 小时前
回溯算法实战练习(3)
javascript·后端·算法
小王不爱笑1326 小时前
G1 GC 的核心基础:Region 模型的补充细节
java·jvm·算法
小王不爱笑1327 小时前
三色标记算法
算法
小O的算法实验室7 小时前
2026年AST SCI1区TOP,基于速度障碍法的多无人机三维避障策略,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
AlenTech8 小时前
141. 环形链表 - 力扣(LeetCode)
数据结构·leetcode·链表
U-52184F698 小时前
深入理解“隐式共享”与“写时复制”:从性能魔法到内存深坑
java·数据库·算法
pp起床8 小时前
Part02:基本概念以及基本要素
大数据·人工智能·算法