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.
  • 0,1,4,4,5,6,7 if it was rotated 7 times.

Notice that rotating an array a\[0, a1, a2, ..., an-1] 1 time results in the array a\[n-1, a0, a1, a2, ..., an-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 <= numsi <= 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 numsmid is greater than numsright, the minimum is in the right half (excluding mid), so move left to mid + 1.
  • If numsmid is less than numsright, the minimum could be mid or to the left of mid, so move right to mid.
  • If numsmid equals numsright, 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];
}
相关推荐
大白话_NOI4 分钟前
【洛谷 P2678】 [NOIP2015 提高组] 跳石头 超详细题解
c++·算法
xwz小王子7 分钟前
ICRA 2026深度观察:全栈闭环成标配,中国具身智能势力显著崛起
大数据·人工智能·算法
孬甭_8 分钟前
深入解析归并排序:稳定高效的分治典范
算法·排序算法
DXM052116 分钟前
第14期|高阶分割模型:Transformer/SegFormer遥感应用
人工智能·python·神经网络·算法·计算机视觉·cnn·ageo
Kurisu_红莉栖1 小时前
前缀和的另外一种用法,前缀和分解
算法
88号技师1 小时前
2026年2月一区SCI-交叉传播优化算法Propagation Alongside Crossover-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
悠仁さん1 小时前
数据结构 图(代码实现篇 C语言版)
数据结构·算法·图论
aini_lovee1 小时前
多智能体粒子群优化(Multi-Agent Particle Swarm Optimization, MAPSO)
算法
A.零点1 小时前
【2个月 C 语言从入门到精通:零基础系统教程】第十二讲:深入了解指针(五)
c语言·开发语言·网络·笔记·visual studio
周末也要写八哥1 小时前
贪心法求经典算法题——最低加油次数
算法