[LeetCode] Find Minimum in Rotated Sorted Array II

本文介绍了一种解决寻找旋转排序数组中最小值的方法,该问题与查找旋转排序数组中的最小值类似,但存在重复元素。文章详细阐述了如何通过设置左右指针并利用不变量来解决这一问题,当无法排除一半的搜索范围时,采用线性搜索完成。

This problem is more or less the same as Find Minimum in Rotated Sorted Array. And one key difference is as stated in the solution tag. That is, due to duplicates, we may not be able to throw one half sometimes. And in this case, we could just apply linear search and the time complexity will become O(n).

The idea to solve this problem is still to use invariants. We set l to be the left pointer and r to be the right pointer. Since duplicates exist, the invatiant is nums[l] >= nums[r] (if it does not hold, then nums[l] will simply be the minimum). We then begin binary search by comparingnums[l], nums[r] with nums[mid].

  1. If nums[l] = nums[r] = nums[mid], simply apply linear search within nums[l..r].
  2. If nums[mid] <= nums[r], then the mininum cannot appear right to mid, so set r = mid;
  3. If nums[mid] > nums[r], then mid is in the first larger half and r is in the second smaller half, so the minimum is to the right of mid: set l = mid + 1.

The code is as follows.

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         int l = 0, r = nums.size() - 1;
 5         while (nums[l] >= nums[r]) {
 6             int mid = (l & r) + ((l ^ r) >> 1);
 7             if (nums[l] == nums[r] && nums[mid] == nums[l])
 8                 return findMinLinear(nums, l, r);
 9             if (nums[mid] <= nums[r]) r = mid;
10             else l = mid + 1;
11         }
12         return nums[l];
13     } 
14 private:
15     int findMinLinear(vector<int>& nums, int l, int r) {
16         int minnum = nums[l];
17         for (int p = l + 1; p <= r; p++)
18             minnum = min(minnum, nums[p]);
19         return minnum;
20     }
21 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4659011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值