• 旋转数组的最小数字


    题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

    思路:1.暴力遍历时间复杂度是O(N);

       2.采用二分查找法的时间复杂度是O(lgN);

    int FindMinValue(int arrValue[], int length)
    {
    	if (arrValue == nullptr || length <= 0)
    		throw new std::exception("Invalid parameters");
    
    	int lowIndex = 0;
    	int midIndex = 0;
    	int highIndex = length - 1;
    	if (arrValue[lowIndex] < arrValue[highIndex])
    		return arrValue[lowIndex];
    
    	while (lowIndex < highIndex)
    	{
    		midIndex = (highIndex - lowIndex) / 2 + lowIndex;
    		if (arrValue[midIndex] > arrValue[lowIndex])
    			lowIndex = midIndex;
    		else if(arrValue[midIndex] < arrValue[lowIndex])
    			highIndex = midIndex;
    		else
    		{
    			if (arrValue[lowIndex] == arrValue[highIndex])
    				highIndex--;
    			else
    				lowIndex = midIndex;
    		}
    		if (highIndex - lowIndex == 1)
    			return arrValue[highIndex];
    	}
    	return arrValue[highIndex];
    }
    

      

  • 相关阅读:
    安装Python及工具
    Python能做什么
    学习Python前序
    [摘]selenium-ide命令
    [摘]selenium-ide编辑命令
    selenium-ide学习
    敏捷个人课后练习:管理情绪
    敏捷个人课后练习:释放情绪
    敏捷个人课后练习:接纳情绪
    敏捷个人课后练习:承诺
  • 原文地址:https://www.cnblogs.com/yapp/p/9042775.html
Copyright © 2020-2023  润新知