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];
}
相关推荐
程序猿小D6 分钟前
第30节 Node.js C/C++ 插件
c语言·c++·后端·node.js·vim
liulilittle7 分钟前
通过高级处理器硬件指令集AES-NI实现AES-256-CFB算法。
linux·服务器·c++·算法·安全·加密·openssl
W说编程11 分钟前
算法导论第一章:算法基础与排序艺术
c语言·数据结构·算法
titan TV man12 分钟前
上海市计算机学会竞赛平台2022年5月月赛丙组最远城市距离
数据结构·算法
慢半拍iii9 小时前
数据结构——D/串
c语言·开发语言·数据结构·c++
王景程9 小时前
什么是哈希函数
算法·哈希算法
会不再投降2199 小时前
《算法复杂度:数据结构世界里的“速度与激情”》
数据结构·算法
kaiaaaa9 小时前
算法训练第十五天
开发语言·python·算法
Coovally AI模型快速验证10 小时前
SLAM3R:基于单目视频的实时密集3D场景重建
神经网络·算法·3d·目标跟踪·音视频
whoarethenext10 小时前
使用 C/C++ 和 OpenCV 提取图像的感兴趣区域 (ROI)
c语言·c++·opencv