您的位置:首页 > Web前端

剑指offer——旋转数组的最小值

2016-06-14 21:27 288 查看
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。

输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。

例如数组{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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: