题解 |滑动窗口

罪犯转移

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);
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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