关闭

LeetCode——Find Minimum in Rotated Sorted Array

标签: leetcode算法
175人阅读 评论(0) 收藏 举报
分类:

题目:

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.

解答:

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

        bool isRising = nums[0] < nums[1];
        int rtn = (isRising ? nums[0] : nums[nums.size() - 1]);
        for (int i = 1; i != nums.size(); ++i) {
            if (isRising && nums[i] < nums[i - 1]) {
                return nums[i];
            }

            if (!isRising && nums[i] > nums[i - 1]) {
                return nums[i - 1];
            }
        }
        return rtn;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24779次
    • 积分:837
    • 等级:
    • 排名:千里之外
    • 原创:48篇
    • 转载:7篇
    • 译文:0篇
    • 评论:2条
    最新评论