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];
}
相关推荐
小李飞刀李寻欢4 小时前
DeepSeek V3 版本模型结构分析
算法·大模型·deepseek
某不知名網友5 小时前
C++ 七大排序算法完整讲解
java·算法·排序算法
得物技术5 小时前
得物推荐系统诊断 Agent:从 “调接口” 到 “会思考”|AICon 演讲整理
人工智能·算法·架构
Lugas5 小时前
为啥说男生找对象尽量在25岁前找到?
算法
MrZhao4005 小时前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
薄情书生5 小时前
基于51单片机的电子钟设计(LCD12864显示 + DS1302)
c语言·51单片机·protues
QN1幻化引擎6 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
半条-咸鱼6 小时前
【FreeRTOS】核心原理与实战速查手册
c语言·操作系统·rtos
白帽小阳6 小时前
Typora插件开发指南:打造专属IDE式写作环境
c语言·网络·python·网络安全·github·pygame·护网行动
学计算机的计算基6 小时前
LeetCode 图论四题精讲:BFS、拓扑排序、Trie 树的模板与优化
java·笔记·算法