温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

旋转数组中的最小数字

发布时间:2020-07-09 15:55:25 来源:网络 阅读:341 作者:duanjiatao 栏目:编程语言

题目描述:把一个数组最开始的若干个元素移动到数组的末尾,称之为一个数组的旋转。输入一个递增排序的数组的旋转,输出旋转数组的最小元素。


例如:数组 {3,4,5,1,2} 为{1,2,3,4,5} 的一个旋转,该数组的最小元素为 1。

分析:旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

int Min(int* numbers, int length)
{
    if(numbers == NULL || length <= 0)
        throw new std::exception("Invalid parameters");
 
    int index1 = 0;
    int index2 = length - 1;
    int indexMid = index1;
    while(numbers[index1] >= numbers[index2])
    {
        // 如果index1和index2指向相邻的两个数,
        // 则index1指向第一个递增子数组的最后一个数字,
        // index2指向第二个子数组的第一个数字,也就是数组中的最小数字
        if(index2 - index1 == 1)
        {
            indexMid = index2;
            break;
        }
 
        // 如果下标为index1、index2和indexMid指向的三个数字相等,
        // 则只能顺序查找
        
        indexMid = (index1 + index2) / 2;
        // 缩小查找范围
        if(numbers[indexMid] >= numbers[index1])
            index1 = indexMid;
        else if(numbers[indexMid] <= numbers[index2])
            index2 = indexMid;
    }
 
    return numbers[indexMid];
}

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

旋转数组中的最小数字

int Min(int* numbers, int length)
{
    if(numbers == NULL || length <= 0)
        throw new std::exception("Invalid parameters");
 
    int index1 = 0;
    int index2 = length - 1;
    int indexMid = index1;
    while(numbers[index1] >= numbers[index2])
    {
        // 如果index1和index2指向相邻的两个数,
        // 则index1指向第一个递增子数组的最后一个数字,
        // index2指向第二个子数组的第一个数字,也就是数组中的最小数字
        if(index2 - index1 == 1)
        {
            indexMid = index2;
            break;
        }
 
        // 如果下标为index1、index2和indexMid指向的三个数字相等,
        // 则只能顺序查找
        indexMid = (index1 + index2) / 2;
        if(numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])
            return MinInOrder(numbers, index1, index2);

        // 缩小查找范围
        if(numbers[indexMid] >= numbers[index1])
            index1 = indexMid;
        else if(numbers[indexMid] <= numbers[index2])
            index2 = indexMid;
    }
 
    return numbers[indexMid];
}

int MinInOrder(int* numbers, int index1, int index2)
{
    int result = numbers[index1];
    for(int i = index1 + 1; i <= index2; ++i)
    {
        if(result > numbers[i])
            result = numbers[i];
    }

    return result;
}

旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字旋转数组中的最小数字

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI