编程题-旋转数组的最小数字

编程题-旋转数组的最小数字

题目

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

输入
[3,4,5,1,2]
输出
1

解析

使用二分法,还要考虑到特殊情况如0,1,1,1,1

c# 代码

class Program
    {

        static void Main(string[] args)
        {
            int[] a = { 3, 4, 5, 6, 7, 1, 2 };
            int[] b = { 0, 1, 1, 1, 1 };
            int[] c = { };
            int[] d = { 1 };
            int[] e = { 1, 2 };
            Program.minNumberInRotateArray(e);
            Console.Read();
        }

        public static int minNumberInRotateArray(int[] rotateArray)
        {
            if (rotateArray == null || rotateArray.Length == 0)
                return 0;
            int firstPoint = 0;
            int lastPoint = rotateArray.Length - 1;
            int minNumber=FindMinNumber(rotateArray, firstPoint, lastPoint);
            return minNumber;
        }

        public static int FindMinNumber(int [] rotateArray,int firstPoint,int lastPoint)
        {
            int middlePoint = (firstPoint + lastPoint) / 2;
            if (firstPoint == lastPoint)
                return rotateArray[firstPoint];
            if (middlePoint == firstPoint || middlePoint == lastPoint)
                return (rotateArray[firstPoint] <= rotateArray[lastPoint]) ? rotateArray[firstPoint] : rotateArray[lastPoint];

            if(rotateArray[lastPoint]<=rotateArray[middlePoint] && rotateArray[firstPoint]>=rotateArray[lastPoint])
                return FindMinNumber(rotateArray, middlePoint, lastPoint);

            if (rotateArray[middlePoint]<=rotateArray[lastPoint])
                return FindMinNumber(rotateArray, firstPoint, middlePoint);
            return 0;
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值