找出最长连续子序列,要求最多很有3个不同的数

本文介绍了一个算法,用于在数组中找到包含至多三个唯一元素的最大连续子序列长度。时间复杂度为O(n),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 找出最长连续子序列,要求最多很有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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值