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.