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;
}


你可能感兴趣的:(Find minimum number in Rotated sorted array.)