题目八:旋转数组的最小数字
Posted yzdai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题目八:旋转数组的最小数字相关的知识,希望对你有一定的参考价值。
/////////////////////////////////////////////////////////////////////////////////////////////
//12. 题目八:旋转数组的最小数字
int RotatedBinarySearchMinNum(int aiArray[], int iLen) int iLeft = 0; int iMid = 0; int iRight = iLen - 1; while (aiArray[iLeft] >= aiArray[iRight]) if (iRight - iLeft == 1) iMid = iRight; break; iMid = iLeft + (iRight - iLeft) / 2; if (aiArray[iMid] >= aiArray[iLeft]) iLeft = iMid; else if (aiArray[iMid] <= aiArray[iRight]) iRight = iMid; return aiArray[iMid]; // 旋转数组中查找 int RotatedBinarySearch(int aiArray[], int iLen, int iTarget) int iLeft = 0; int iMid = 0; int iRight = iLen - 1; while (iLeft <= iRight) iMid = iLeft + (iRight - iLeft) / 2; if (aiArray[iMid] == iTarget) return iMid; // 情况一:旋转点在中位数的右侧 if (aiArray[iMid] >= aiArray[iLeft]) // 最左侧元素 <= 查找目标 < 中位数 if (aiArray[iLeft] <= iTarget && iTarget < aiArray[iMid]) iRight = iMid - 1; else iLeft = iMid + 1; // 情况二: 旋转点在中位数的左侧 else // 中位数 < 查找目标 <= 最右侧元素 if (aiArray[iMid] < iTarget && iTarget <= aiArray[iRight]) iLeft = iMid + 1; else iRight = iMid - 1; return -1; void RotatedBinarySearchTestFunc() cout << "\n\n --------------- RotatedBinarySearchTestFunc Start -------------->" << endl; int aiArray[] = 9, 10, 11, 12, 13, 1, 3, 4, 5, 8; int iLen = sizeof(aiArray) / sizeof(int); TRAVERSAL_ARRAY(aiArray, iLen); cout << "旋转数组中最小数字: " << RotatedBinarySearchMinNum(aiArray, iLen) << endl; int iFindNum = 5; int iIndex = RotatedBinarySearch(aiArray, iLen, iFindNum); if (iIndex > 0) printf("Find %02d[%02d] Success!", iFindNum, iIndex); else cout << "Find: " << iFindNum << " Failed!" << endl; cout << "\n\n --------------- RotatedBinarySearchTestFunc Start -------------->" << endl;
以上是关于题目八:旋转数组的最小数字的主要内容,如果未能解决你的问题,请参考以下文章