
题目
解决代码及点评
/* 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个 排好序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3, 4, 5, 1, 2}为{1, 2, 3, 4, 5} 的一个旋转,该数组的最小值为 1。 */ #include <iostream> using namespace std; int FindMin(int *pnArr, int nLen) { if (pnArr == NULL || nLen < 1) { exit(0); } int nLeft = 0; int nRight = nLen - 1; int nMid; //旋转个数为0 直接返回第一个元素 if (pnArr[nLeft] < pnArr[nRight]) { return pnArr[nLeft]; } // 通过二分去查找最小元素 while (nLeft <= nRight) { nMid = nLeft + (nRight - nLeft) / 2; if (pnArr[nLeft] < pnArr[nMid]) // 左边的是递增数组 { nLeft = nMid; // 那么最小的元素在右边 } else if (pnArr[nLeft] > pnArr[nMid]) // 如果右边是递增数组 { nRight = nMid; // 那么最小的元素在左边 } else {//pnArr[nLeft] == pnArr[nMid] return pnArr[nLeft + 1]; } } } int main() { int nArr[ ] = {5,6,7,8,9,10,2,3,4}; cout<<FindMin(nArr, sizeof(nArr)/sizeof(int))<<endl; system("pause"); return 0; }
代码下载及其运行
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果