题目:数组中最长的区间,满足该区间内的数排序后是连续的。比如,[23, 4,1,3,2,9,8,24] 4,1,3,2 是最长区间,是连在一起的。[23, 1,3,2,9,4,8,24] 就只能返回1,2,3了。
算法描述:
①从x0开始,找length=|x0-x1|+1内的max和min,length大于数列长度则否定x0,再从x1向后开始找;1_如果max-min+1=length,则区间连续,记录length,继续向后添加一个元素,判断是否为max+1或min-1,若是,则length++,继续向后并更新max或min,直到否或数列尾,若否,则临时更新为max0或min0
#include <stdio.h>
/*
* Author : Tian Mo
*
* Date : 2013-06-17 14:00
*
* Locate : Baidu PS, Beijing
*/
int GetMaxAndMinFromArray (const int *v, const int len, const int start, \
const int end, int *max, int *min)
{
if (NULL == v || start < 0 || end >= len || end < start)
{
return -1;
}
int i;
int tempMax = v[start];
int tempMin = v[start];
for(i = start; i < end + 1; ++ i)
{
if (v[i] > tempMax)
{
tempMax = v[i];
}
if (v[i] < tempMin)
{
tempMin = v[i];
}
}
*max = tempMax;
*min = tempMin;
return 0;
}
int GetMaxSeqStartAndEnd(const int *v, const int len, int *iStart, int *iEnd)
{
if (NULL == v || len <= 0)
{
return -1;
}
int i, j, start, end, CurLen, CurMax, CurMin;
/* supress call function error result to the pointer of iStart & iEnd error */
start = end = 0;
int MaxLen = 0;
for(i = 0; i < len - 1; ++ i)
{
CurLen = 0;
for(j = i + 1; j < len - 1; ++ j)
{
if (-1 == GetMaxAndMinFromArray(v, len, i, j, &CurMax, &CurMin))
{
printf("Call Function Error.\n\n");
continue;
}
else
{
CurLen = CurMax - CurMin + 1;
if (CurLen == j - i + 1)
{
if (CurLen > MaxLen)
{
start = i;
end = j;
MaxLen = CurLen;
}
}
}
}
}
*iStart = start;
*iEnd = end;
return 0;
}
int main()
{
//[23, 4,1,3,2,9,8,24] => 4,1,3,2
//int v[] = {23, 4,1,3,2,9,8,24};
//[23, 1,3,2,9,4,8,24] => 1, 2, 3
int v[] = {23, 1,3,2,9,4,8,24};
const int len = sizeof(v) / sizeof(v[0]);
int i,begin,end;
GetMaxSeqStartAndEnd(v, len, &begin, &end);
for(i = begin; i <= end; ++ i)
{
printf("%2d", v[i]);
}
printf("\n");
}