7月8日训练总结

双指针算法

牛客上遇到一个问题,可以用尺取+离散化做,但是尺取本质上也是双指针算法,所以复习一下双指针算法

题目描述

Farmer John’s N cows (1 <= N <= 100,000) are lined up in a row. Each cow is identified by an integer “breed ID” in the range 0…1,000,000,000; the breed ID of the ith cow in the lineup is B(i). Multiple cows can share the same breed ID.
FJ thinks that his line of cows will look much more impressive if there is a large contiguous block of cows that all have the same breed ID. In order to create such a block, FJ chooses up to K breed IDs and removes from his lineup all the cows having those IDs. Please help FJ figure out the length of the largest consecutive block of cows with the same breed ID that he can create by doing this.

输入描述:

  • Line 1: Two space-separated integers: N and K.

  • Lines 2…1+N: Line i+1 contains the breed ID B(i).

输出描述:

  • Line 1: The largest size of a contiguous block of cows with
    identical breed IDs that FJ can create.

示例1

输入
9 1
2
7
3
7
7
3
7
5
7
输出
4

说明

INPUT DETAILS:
There are 9 cows in the lineup, with breed IDs 2, 7, 3, 7, 7, 3, 7, 5, 7.
FJ would like to remove up to 1 breed ID from this lineup.

OUTPUT DETAILS:
By removing all cows with breed ID 3, the lineup reduces to 2, 7, 7, 7, 7,
5, 7. In this new lineup, there is a contiguous block of 4 cows with the
same breed ID (7).

AC代码

#include<bits/stdc++.h>
using namespace std;
map<long long,int> vis;
int a=0,r=0,l=1,x[100005],ans=0;
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>x[i];
	}
	while(r<=n){
		r++;
		if(!vis[x[r]]){
			a++;
		}
		vis[x[r]]++;
		while(a==k+2){
			vis[x[l]]--;
			if(!vis[x[l]]){
				a--;
			}
			l++;
		}
		ans=max(ans,vis[x[r]]);
	}
	cout<<ans;
	return 0;
}

分析

题意是给定一段序列,
Acwing上两题作为练习:

799. 最长连续不重复子序列

给定一个长度为n的整数序列,请找出最长的不包含重复数字的连续区间,输出它的长度。

输入格式

第一行包含整数n。

第二行包含n个整数(均在0~100000范围内),表示整数序列。

输出格式

共一行,包含一个整数,表示最长的不包含重复数字的连续子序列的长度。

数据范围

1≤n≤100000

输入样例:

5
1 2 2 3 5

输出样例:

3

AC代码:

#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f 
const int maxn=1e5+10;
 
int a[maxn],s[maxn],n,ans=1;

int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	
	for(int i=1,j=1;i<=n;i++){
		s[a[i]]++;
		while(j<i&&s[a[i]]>1){
			s[a[j]]--;
			j++;
		} 
		int t=i-j+1;
		ans=max(ans,t);
	}
	
	printf("%d",ans);
	return 0;
}

分析

今日感悟:
搞清楚算法,做相关题以后,明天要留出来时间做比赛题,比赛的时候是不知道用什么算法的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值