Java题解 | 滑动窗口解决

小红的01子序列构造(easy)

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

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long k = in.nextLong();
        in.nextLine();
        String s = in.nextLine();
        char[] c = s.toCharArray();
        int l = 0, r = 0, x = 0, y = 0;
        long cnt = 0;
        while (r < n) {
            if (c[r++] == '0') x++;
            else {
                y++;
                cnt += x;
            }
            while (cnt > k) {
                if (c[l++] == '0') {
                    x--;
                    cnt -= y;
                }else y--;
            }
            if (cnt == k) break;
        }
        if (cnt == k) System.out.printf("%d %d", l + 1, r);
        else System.out.print(-1);
        in.close();
    }
}

维护窗口内0的数量和1的数量,以及01对数量,计为x、y和cnt。

当cnt小于k时窗口向右扩张,遇到1时cnt+=x;遇到0时y++。

当cnt大于k时窗口左端点右移,如果去掉的是0,cnt-=y,x--;去掉的是1,y--。

cnt等于k时break

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:15
点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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