旋转数组中的最小数字

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

成都创新互联主要从事成都网站制作、网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务惠来,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

例如:数组 {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;
}

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

本文题目:旋转数组中的最小数字
文章URL:https://www.cdcxhl.com/article22/jjppjc.html

成都网站建设公司_创新互联,为您提供手机网站建设网站策划网站维护商城网站外贸网站建设定制网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站制作