AcWing 799. 最长连续不重复子序列(Double pointer) Described by Java

I didn’t think that the familiar double-pointer algorithm unexpectedly
took half a whole day. Fuck me.
Get the problem first :
给定一个长度为n的整数序列,请找出最长的不包含重复数字的连续区间,输出它的长度。

输入格式
第一行包含整数n。

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

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

数据范围
1≤n≤100000
输入样例:
5
1 2 2 3 5
输出样例:
3


First, violence can solve it in O(n2) , but it’s use too much time.The correct is to use L and R points to travel array and only solve in O(n) (once travel)

It’s easy to understand the double-pointer , but I do not know where my bug is.
The AC code :

import java.io.*;
public class Main{
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter pw = new PrintWriter(System.out);
    static int nums[], n;
    public static void main(String []args) throws Exception {
        st.nextToken();
        n = (int)st.nval;
        nums = new int[n];
        for (int i = 0; i < n; i++ ) {
            st.nextToken();
            nums[i] = (int)st.nval;
        }
        int max = 0;
        int check[] = new int[100001];
        for (int r = 0, l = 0; r < n; r ++) {
            check[nums[r]] ++;
            while (l < r && check[nums[r]] > 1) {
                check[nums[l]] --;
                l++;
            } 
            max = Math.max(max, r - l + 1);
        }
        pw.println(max);
        pw.flush();
    }
}

check[] is to record the times num appeared.


The WA code :

import java.io.*;
public class Main{
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter pw = new PrintWriter(System.out);
    static int nums[], n;
    public static void main(String []args) throws Exception {
        st.nextToken();
        n = (int)st.nval;
        nums = new int[n];
        for (int i = 0; i < n; i++ ) {
            st.nextToken();
            nums[i] = (int)st.nval;
        }
        int max = 0, j = 0;
        for (int i = 0; i < n; i++) {
            boolean check[] = new boolean[100000];
            for (j = i; j < n; j++) {
                if (!check[nums[j]]) {
                    check[nums[j]] = true;
                }
                else {
                    break;
                }
            }
            max = Math.max(max, j - i );
            i = j;
        }
        pw.println(max);
        pw.flush();
    }
}

check[index] is to record if num has appeared.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值