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];
}
相关推荐
203号居民15 分钟前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21031 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2081 小时前
leetcode 78子集
数据结构·算法·leetcode
en.en..2 小时前
Linux fork() 工作原理
数据结构·算法
地平线开发者3 小时前
bevformer算法模型详细解读
算法
liliangcsdn3 小时前
ICIR权重矩阵如何加权标准化为综合因子
算法
是隼人3 小时前
buuctf-pwn mrctf2020_easy_equation(64位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
AC赳赳老秦3 小时前
文旅市场公开数据分析:基于 OpenClaw 采集景区客流与门票公示数据,生成区域文旅热度监测报告
java·c语言·python·php·symfony·deepseek·openclaw
HRTOS3 小时前
HRTOS应用示例:信号量机制详解
c语言·人工智能·嵌入式硬件·51单片机
SDWAN_Cheap4 小时前
SD-WAN智能选路技术的算法与实现机制
算法·php·sdwan