题解 |滑动窗口

罪犯转移

https://www.nowcoder.com/practice/b7b1ad820f0a493aa128ed6c9e0af448

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static int[] nums;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int t = in.nextInt();
            int c = in.nextInt();
            nums = new int[n];
            for(int i=0;i<n;i++){
                nums[i]= in.nextInt();
            }
            int left =0;
            int right = 0;
            //一般用来记录窗口内有效字符个数  这里可以用queue的长度代替
            int vaild = 0;
            int sum = 0;
            int count=0;
            LinkedList<Integer> queue = new LinkedList<>();
            while(right<n){
                //需要加入窗口的字符
                int num = nums[right];
                right++;
                //用双端队列存储
                queue.add(num);
                sum+=num;
                //不符合条件缩小窗口
                while(sum>t || queue.size()>c){
                    int temp = queue.pollFirst();
                    sum-=temp;
                    left++;
                }
                if(queue.size()==c && sum<=t){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}

全部评论

相关推荐

10-22 12:03
山东大学 Java
程序员小白条:26届一般都得有实习,项目可以随便写的,如果不是开源社区的项目,随便包装,技术栈也是一样,所以本质应该找学历厂,多投投央国企和银行,技术要求稍微低一点的,或者国企控股那种,纯互联网一般都得要干活
应届生简历当中,HR最关...
点赞 评论 收藏
分享
09-17 17:09
门头沟学院 Java
雨忄:有人给出过解法,拖晚点去,然后到时候再找其他理由商量,既增加他们的筛人成本,不一定会给你收回offer ,也能占位避免工贼
秋招的嫡长offer
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务