LeetCode 153. Find Minimum in Rotated Sorted Array

题目描述

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

大意就是找到旋转数组中的最小值;

解答

  可以发现,经过旋转后的数组保持着 “块状” 有序性,如4,5,6,7保持有序,0,1,2保持有序。既然有序,就可以采用binary search进行查找。

  先对 r 和 l 处的元素进行比较;若 l 处较大,则最小元素在 l 的右侧,l++;否则,数组本身是升序的,直接返回 l 处的元素。

  

class Solution {
public:
    int findMin(vector<int>& nums) {
        int n = nums.size()-1;
        int l = 0;
        int r = n;
        while(l < r){
            int mid = l + (r - l)>>1;
            if(nums[l] > nums[r])
                l++;
            else
                return nums[l];
        }
        return nums[l];
        
    }
};

 

posted @ 2019-11-01 10:07  3/8  阅读(79)  评论(0编辑  收藏  举报