Find Minimum in Rotated Sorted Array

Description

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.

Notice
You may assume no duplicate exists in the array.
Example
Given [4, 5, 6, 7, 0, 1, 2] return 0

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution {
public:
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    int findMin(vector<int> &nums) {
        // write your code here
        if (nums.empty()) {
            return -1;
        }
        // the comp val must get the boundary value
        // if the sorted array has not shifting, the nums[0] will not be met requ.
        int comp = nums[nums.size()-1];
        int start = 0;
        int end = nums.size()-1;
        while (start+1 < end) {
            int mid = start + (end-start)/2;
            // mid in the first part, so the min is in the back of mid
            if (nums[mid] > comp) {
                start = mid;
            } else {
            // mid in the second part, so the min is in the front of mid
                end = mid;
            }
        }
        if (nums[start] < nums[end]) {
            return nums[start];
        } else {
            return nums[end];
        }
        return -1;
    }
};
// 4 5 6 mid 7 0 1 2 
// 0 1 2 mid 4 5 6 7

Similar problems

x

Tags

x

results matching ""

    No results matching ""