Find Minimum in Rotated Sorted Array II--LeetCode

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

The array may contain duplicates.

思路:可能有重复,那么就需要慢慢的移动了

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int FindMin(vector<int>& vec)
{
    int low=0,high = vec.size()-1;
    int mid,minnum;
    minnum = vec[0];
    while(low<= high)
    {
      mid = low+ (high-low)/2;
      cout<<mid<<endl;
      if(high-1 == low)
       minnum = min(minnum,min(vec[low],vec[high]));
      if(vec[low] < vec[mid]) // 升序
      {
          minnum = min(minnum,vec[low]);
          low = mid+1;       
      }                
      else if(vec[mid] < vec[high])
      {
         minnum = min(minnum,vec[mid]);
         high = mid-1;    
      }     
      else
         low++;     
    } 
    return minnum;
}
int main()
{
    int array[] = {9,8,7,6,5,4,3,2,1};
    vector<int> vec(array,array+sizeof(array)/sizeof(array[0]));
    cout<<FindMin(vec);
    system("pause"); 
    return 0;
    } 
ps:为什么第三种情况下,使用的是low++呢,因为这个数组中可能出现了重复的数导致了vec[low] == vec[mid] ==vec[high],这个时候需要low++,或者是整个数组发生了全旋转,导致了vec[low]最大

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值