腾讯2019 暑期实习提前批笔试 —— AcWing 570. 气球游戏

【题目描述】

在这里插入图片描述
在这里插入图片描述
AcWing 570. 气球游戏

【思路】

双指针,i在右,j在左。i从左至右依次扫描,每扫描一个相应更新s[ c[i] ]和颜色数colors,当颜色数达到要求m时,尝试移动j指针使得在满足colors==m的情况下,j离i越近越好。因此j的移动是有条件的,即:
s[ c[j] ] > 1 || c[j] == 0

import java.util.Scanner;

public class Main{
    static int N = 1000010, M = 2010;
    static int c[] = new int[N];// 序列数字
    static int s[] = new int[M]; //s[i] 表示 编号为i的气球个数
    public static void main(String args[]){
        
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt(), m =  reader.nextInt();
        for(int i = 0; i < n; i ++) c[i] = reader.nextInt();
        
        //colors用于统计[i,j]区间的颜色种类数
        int colors = 0;
        
        int ans = n + 1;
        // 双指针 i在右 j在左
        for(int i = 0, j = 0; i < c.length; i ++)
        {
            //如果打中且打中的颜色没有出现过
            if( c[i] != 0 && s[ c[i] ] == 0 ) colors ++;
            s[ c[i] ] ++;
            
            if( colors == m){// j指针尽可能地向i指针靠齐
                while( s[ c[j] ] > 1   ||  c[j] == 0 ){
                    s[ c[j] ] --;
                    j ++;
                }
                ans = Math.min( ans, i - j + 1);
            }
        }
        ans = (ans > n )? -1 : ans;
        System.out.println(ans);
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值