Algorithm review notes (ONE DAY)

Algorithm: Double pointer optimization

Insert image description hereCode:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int arr[100001],cnt[100001];//cnt是记录不同数字的个数
int main()
{
    
    
	int res=0;//记录最大的子区间
	int n;
	int i,j,s;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
		scanf("%d",&arr[i]);
	for(i=0,j=0,s=0;i<n;i++)
	{
    
    
		if(!cnt[arr[i]]) s++; //s记录出现不同数的个数
		cnt[arr[i]]++;
		
		while(s>2)
		{
    
    
			cnt[arr[j]]--;
			if(!cnt[arr[j]]) s--;
			j++;
		}
		res = max(res,i-j+1);
	}
	printf("%d",res);
	return 0;
}

Summary of this question:
This question is mainly to determine that there can only be two unequal numbers in a longest subsequence. Only when the different numbers are 2, can it be guaranteed The longest subsequence is the smallest.
can be solved using double pointer optimization.
The condition for using double pointer optimization is: i is an increasing function with respect to j, that is, as i increases, j also increases.

Insert image description hereMethod 1 (reverse method):

#include<iostream>
#include<cstring>
#include<algorithm>
#include<unordered_set>//hash表
using namespace std;
const int N = 200011;
int main()
{
    
    
	char str[N][11];
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
    
    
		scanf("%s",str[i]);
	}
	unordered_set<string> hash;//开这个hash表是为了记录出现的字符串的次数
	for(int i=n-1;i>=0;i--)
	{
    
    
		if(!hash.count(str[i]))
		{
    
    
			puts(str[i]);
			hash.insert(str[i]);
			}	
	}
	return 0;
}

Method 2 can be done using a double linked list, forward derivation

Guess you like

Origin blog.csdn.net/m0_73728268/article/details/130452536