您的位置:首页 > 职场人生

【面试题】寻找旋转排序数组中的最小值

2015-07-11 21:42 309 查看

题目描述

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。你需要找到其中最小的元素。http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array/

解题思路

基本思想采用二分查找,不过首先要判断这个排序数组是否直接有序,如果是0 1 2 3 4 5 6 7这样的数组,最小值就是第一个值;接着就采用二分法来查找

代码实现

[code]class Solution {
public:
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    int findMin(vector<int> &num) {
        // write your code here
        int len = num.size();

        int low = 0;
        int high = len - 1;

        if(num[low] < num[high])
            return num[low];

        while(high - low > 1)
        {
            int mid = (high + low) / 2;

            if(num[mid] > num[low])
            {
               low = mid; 
            }

            else
            {
                high = mid;
            }
        } 

        return num[high];
    }
};


[code]class Solution {
public:
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    int findMin(vector<int> &num) {
        // write your code here
        int len = num.size();

        int low = 0;
        int high = len - 1;
        int min_index = low;

        while(num[low] >= num[high])
        {
            if(high - low == 1)
            {
                min_index = high;
                break;
            }

            int mid = (high + low) / 2;

            if(num[low] < num[mid])
                low = mid;
            else
                high = mid;
        }

        return num[min_index];
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: