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];
}
相关推荐
散峰而望1 小时前
【算法练习】算法练习精选:陶陶摘苹果(基础+升级)、Music Notes、字串变换,你能AC几道?
数据结构·c++·算法·leetcode·贪心算法·github·动态规划
暗夜猎手-大魔王1 小时前
转载--Hermes Agent 04 | Agent 主循环:一次对话背后发生了什么
人工智能·python·算法
羊羊一洋1 小时前
GCC __attribute__ 完全指南:从入门到实战
c语言·stm32
手写码匠1 小时前
华为云Flexus+DeepSeek征文|基于华为云Flexus X实例 + Dify + DeepSeek 构建企业级智能知识库问答系统实战
人工智能·深度学习·算法·aigc
吴可可1232 小时前
Win7上开发CAD2004自定义实体全解析
c++·算法
YXXY3132 小时前
二叉树中的深搜算法介绍
算法
zz34572981132 小时前
C语言中字符串常量存储位置
c语言·开发语言·算法·青少年编程
noipp2 小时前
推荐题目:洛谷 P16510 [GKS 2015 #C] gRanks
java·c语言·开发语言·c++·python·算法
程序喵大人2 小时前
从内存/汇编角度看C与C++:指针、引用、对象的底层差异
c语言·汇编·c++·指针·引用·对象
菜菜的顾清寒2 小时前
力扣HOT100(50)动态规划-零钱兑换
算法·leetcode·动态规划