先看题目:

Suppose an array sorted in ascending order 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.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2] 
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

题意为给定一个有序数组,然后找到一个旋转点旋转数组,然后需要找到该数组的最小值。基本上在有序数组上寻找值都和二分查找有关系。仔细分析题意,我们可以知道,最小值的前一个值必定大于它,根据这一点来进行二分查找。比较麻烦的是处理左指针和右指针的移动,我们可以根据mid指针和第一个元素的关系来判断如何移动左右指针,假设中指针的值大于第一个值,则中值属于左半个有序的数组中,左指针应当往中指针移动;假设中值小于第一个值,则中值处于右半个有序数组中,则右指针应当往中值移动。下面是实现代码:

int findMin(vector<int>& nums) {
    if (nums.empty()) {
        return 0;
    }
    int l = 0;
    int r = nums.size() - 1;
    while (l <= r) {
        int mid = l + (r - l) / 2;
        if (mid > 0) {
            if (nums[mid] < nums[mid - 1]) {
                return nums[mid];
            }
        }
        if (nums[mid] >= nums[0]) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    return nums[0];
}
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day