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];
}
相关推荐
苦藤新鸡几秒前
16.求数组除了当前元素的所有乘积
算法·leetcode·动态规划
Benny_Tang2 分钟前
题解:P14841 [THUPC 2026 初赛] 哈姆星与古地球学术行为影响星球文明的考古学分析
c++·算法
WilliamHu.2 分钟前
A2A协议
java·数据结构·算法
Tisfy6 分钟前
LeetCode 1895.最大的幻方:暴力中来点前缀和优化
算法·leetcode·前缀和·矩阵·题解·暴力
deng120413 分钟前
【排序算法总结(1)】
java·算法·排序算法
Remember_99317 分钟前
【数据结构】Java数据结构深度解析:栈(Stack)与队列(Queue)完全指南
java·开发语言·数据结构·算法·spring·leetcode·maven
鱼很腾apoc18 分钟前
【实战篇】 第13期 算法竞赛_数据结构超详解(上)
c语言·开发语言·数据结构·学习·算法·青少年编程
啊阿狸不会拉杆27 分钟前
《数字图像处理》第 12 章 - 目标识别
图像处理·人工智能·算法·计算机视觉·数字图像处理
进击的横打37 分钟前
【车载开发系列】安全算法与安全访问
算法·安全·车载系统
努力学算法的蒟蒻38 分钟前
day59(1.18)——leetcode面试经典150
算法·leetcode·职场和发展