Find minimum number in Rotated sorted array.

if the middle value locates in the first increasing part, the mini value must locate at the lower half, thus, the first pointer

should point to the middle instead.

if the middle value locates in the second increasing part, the mini value must be smaller or equals to the second pointer.

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

/*
  Given a sorted array rotated in some point, find the minimum number.
  Example:
  3, 4, 5, 0, 1, 2
  return 0

  1, 1, 1, 1, 0, 1
  return 0
*/
int minInOrder(vector<int>& nums, int start, int end) {
  int result = nums[start];
  for(int i = start + 1; i <= end; ++i) {
    if(result > nums[i]) result = nums[i];
  }
  return result;
}
int findMinimumNumber(vector<int>& nums) {
  int start = 0;
  int end = nums.size() - 1;
  int indexMid = start;
  while(nums[start] >= nums[end]) {
    if(end - start == 1) {
      indexMid = end;
      break;
    }
    int indexMid = (start + end) / 2;
    // if start, end and indexMid all point to the same number.
    if(nums[start] == nums[end] && nums[indexMid] == nums[start])
      //search linarly. 
      return minInOrder(nums, start, end);

    if(nums[indexMid] >= nums[start]) start = indexMid;
    else if(nums[indexMid] <= nums[end]) end = indexMid;
  }
  return nums[indexMid];
}

int main(void) {
  vector<int> nums{1, 0, 1, 1, 1, 1};
  //vector<int> nums{1, 0, 1, 1, 1, 1};
  cout << findMinimumNumber(nums) << endl;
}

A optimized way: do it as the same as search number in rotated sorted array.

#include "header.h"
using namespace std;

int findMini(vector<int>& nums) {
  if(nums.size() == 0) return -1;
  int left = 0, right = nums.size() - 1;
  while(left < right) {
    int mid = left + (right - left) / 2;
    if(nums[mid] < nums[right]) right = mid;
    else if(nums[mid] > nums[right]) left = mid + 1;
    else right--;
  }
  return nums[right];
}

int main(void) {
  vector<int> nums{0, 1, 1};
  cout << findMini(nums) << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值