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], 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];
}
相关推荐
pianmian132 分钟前
贪心算法.
算法·贪心算法
m0_694938011 小时前
Leetcode打卡:字符串及其反转中是否存在同一子字符串
linux·服务器·leetcode
chenziang11 小时前
leetcode hot 100 二叉搜索
数据结构·算法·leetcode
single5943 小时前
【c++笔试强训】(第四十五篇)
java·开发语言·数据结构·c++·算法
呆头鹅AI工作室4 小时前
基于特征工程(pca分析)、小波去噪以及数据增强,同时采用基于注意力机制的BiLSTM、随机森林、ARIMA模型进行序列数据预测
人工智能·深度学习·神经网络·算法·随机森林·回归
一勺汤4 小时前
YOLO11改进-注意力-引入自调制特征聚合模块SMFA
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·目标跟踪
每天写点bug5 小时前
【golang】map遍历注意事项
开发语言·算法·golang
程序员JerrySUN5 小时前
BitBake 执行流程深度解析:从理论到实践
linux·开发语言·嵌入式硬件·算法·架构
王老师青少年编程5 小时前
gesp(二级)(16)洛谷:B4037:[GESP202409 二级] 小杨的 N 字矩阵
数据结构·c++·算法·gesp·csp·信奥赛
robin_suli6 小时前
动态规划子序列问题系列一>等差序列划分II
算法·动态规划