剑指offer——旋转数组的最小值
2016-06-14 21:27
288 查看
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
RevolveArray.h
test.cpp
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
RevolveArray.h
<strong><span style="font-size:18px;">#pragma once #include <iostream> using namespace std; #include <assert.h> template<class T> T& RevolveArray(T* arr,size_t size,size_t k) { assert(arr); T min = arr[0]; T tmp = 0; while (k--) { tmp = arr[0]; for (int index = 1;index < size;++index) { if (min > arr[index]) { min = arr[index]; } arr[index - 1] = arr[index]; } arr[size-1] = tmp; } return min; }</span></strong>
test.cpp
<strong><span style="font-size:18px;">#define _CRT_SECURE_NO_WARNINGS 1 #include "RevolveArray.h" void test1() { //int arr[] = {1,2,3,4,5}; int arr[] = {8,3,7,2,0}; int size = sizeof(arr)/sizeof(arr[0]); int count = 0; cout<<"请输入需要旋转数组的个数"<<endl; cin>>count; int min = RevolveArray<int>(arr,size,count); for (int i = 0;i < size;i++) { cout<<arr[i]<<" "; } cout<<endl<<"min = "<<min<<endl; } int main() { test1(); system("pause"); return 0; }</span></strong>
相关文章推荐
- js_九九乘法表
- ajax获取json路径方式
- 【HTML5】Web存储
- jQuery中的动画
- 【HTML5】地理定位
- Newtonsoft.dll JSON序列化与反序列化
- ReactiveCocoa学习(二)
- IOError: No wkhtmltopdf executable found: ""
- 【HTML5】Canvas和SVG的区别
- 【HTML5】SVG内联
- Java源代码分析之StringBuffer
- jQuery 菜单项切换
- 【HTML5】Canvas画布
- JSON
- js-表单
- JavaScript基础
- js文件内部导入引用js文件方法
- 【HTML5】拖放(Drag 和 drop)
- [Javascript] delete keyword
- css样式优先级示例