// 找出最长连续子序列,要求最多很有3个不同的数.cpp : Defines the entry point for the console application.
//
/*
Given an array of n numbers with repetition of numbers. You need to find the max length of continuous sub array with at max 3 unique elements.
For eg
array: 1 2 3 1 4 3 4 1 2
ans: 6 (3 1 4 3 4 1)
Solution: Time complexity O(n)
Extra Space O(1)
*/
#include "stdafx.h"
#include <map>
using namespace std;
void findI_J(int A[], int N, int &I, int &J)
{
I = -1;
J = -1;
if (A == NULL || N < 3)
{
return;
}
std::map<int, int> mMap;
int idx = 0;
while (mMap.size() < 3)
{
if (mMap.count(A[idx]) == 0)
mMap[A[idx]] = 1;
else
mMap[A[idx]]++;
idx++;
}
int i = 0, j = idx-1;
int maxDist = j-i;
int maxI = i;
int maxJ = j;
while (j < N-1)
{
j++;
if (mMap.count(A[j]) == 0)
{
mMap[A[j]] = 1;
while (mMap[A[i]] > 1)
{
mMap[A[i]]--;
i++;
}
mMap.erase(A[i]);
i++;
}
else
{
mMap[A[j]]++;
if (j-i > maxDist)
{
maxDist = j-i;
maxI = i;
maxJ = j;
}
}
}
I = maxI;
J = maxJ;
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
int front = -1, rear = -1;
int Array[] = {1,2,3,1,4,3,4,1,2};
findI_J(Array, sizeof(Array)/sizeof(Array[0]), front, rear);
for (int i = front; i <= rear; i++)
{
printf("%d ", Array[i]);
}
printf("\n");
return 0;
}