Find Minimum in Rotated Sorted Array

题目名称
Find Minimum in Rotated Sorted Array—LeetCode链接

描述
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.

You may assume no duplicate exists in the array.

分析
  从1开始遍ector,如果大于前一个数,则继续遍历,知道找到比前面一个数小的数,即为最小元素,如果一次遍历没有发现,则返回第一个数,时间复杂度为Ο(n).

C++代码

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

总结
  一开始以为是个很难的题目,想到用二分法或者分治法,但是觉得可能一次遍历跟好,所以这道题的难度应该放到Easy里面。

你可能感兴趣的:(LeetCode)