最长的可整合子数组的长度
程序员文章站
2022-03-01 17:17:32
...
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <set>
#include <climits>
#include <deque>
#include <ctime>
using namespace std;
bool isLegal(vector<int>& arr, int left, int right)
{
vector<int> newarr(arr.begin() + left, arr.begin() + right + 1);
sort(newarr.begin(), newarr.end());
for(int i = 1; i < newarr.size(); ++i)
if(newarr[i - 1] != newarr[i] - 1)
return false;
return true;
}
//O(n*n*n*logn)
int getL1(vector<int>& arr)
{
if(arr.size() == 0)
return 0;
int length = 0;
for(int i = 0; i < arr.size(); ++i)
for(int j = i; j < arr.size(); ++j)
if(isLegal(arr, i, j))
length = max(length, j - i + 1);
return length;
}
//O(n*n)
int getL2(vector<int>& arr)
{
if(arr.size() == 0)
return 0;
int length = 0;
int imax = 0;
int imin = 0;
set<int> iset;
for(int i = 0; i < arr.size(); ++i)
{
imax = INT_MIN;
imin = INT_MAX;
for(int j = i; j < arr.size(); ++j)
{
if(iset.find(arr[j]) != iset.end())
break;
iset.insert(arr[j]);
imax = max(imax, arr[j]);
imin = min(imin, arr[j]);
if(imax - imin == j - i)
length = max(length, j - i + 1);
}
iset.clear();
}
return length;
}
//以下为对数器部分
// 生成元素为随机数的数组
void Random(vector<int> &arr, int n)
{
int i=0;
srand( (unsigned)time( NULL ) );
while(i<n)
{
arr[i++]=rand() % 10;
// cout << arr[i - 1] << endl;
}
}
int main()
{
#define nsize 10
vector<int> ivec(nsize);
int count = 0;
while(count < 100)
{
Random(ivec, nsize);
if(getL2(ivec) == getL1(ivec))
++count;
else
{
cout << "fail" << endl;
break;
}
}
cout << "success" << endl;
}
下一篇: 最长的可整合子数组的长度