(两元序列)试求一个整数序列中,最长的仅包含两个不同整

(两元序列)试求一个整数序列中,最长的仅包含两个不同整数的连续子序列。如有多个子 序列并列最长,输出任意一个即可。例如,序列“ 1 1 2 3 2 3 2 3 3 1 1 1 3 1 ”中,有 两段满足条件的最长子序列,长度均为 7,分别用下划线和加粗斜体标出。

#include <iostream>
using namespace std;
int main(){
    const int SIZE = 100;
    int n, i, j, a[SIZE], cur1, cur2, count1, count2,
    ans_length, ans_start, ans_end;
    //cur1, cur2 分别表示当前子序列中的两个不同整数
    //count1, count2 分别表示 cur1, cur2 在当前子序列中出现的次数
    cin>>n;
    for (i = 1;i <= n;i++)
        cin>>a[i];
    i = 1;
    j = 1;
    //i, j 分别表示当前子序列的首尾,并保证其中至多有两个不同整数
    while ((j <= n) && (a[j] == a[i]))
        j++;
    cur1 = a[i];
    cur2 = a[j];
    count1 =①;
    count2 = 1;
    ans_length = j - i + 1;
    while (j < n) {
        j++;
        if (a[j] == cur1)
            count1++;
        else if (a[j] == cur2)
            count2++;
        else {
            if (a[j - 1] ==② ) {
                while (count2 > 0) {
                    if (a[i] == cur1)
                        count1--;
                    else
                        count2--;
                    i++;
                }
                cur2 = a[j];
                count2 = 1;
            }else {
                while (count1 > 0) {
                    if (a[i] == cur1)
                        ③ ;
                    else
                        ④ ;
                    i++;
                }
                ⑤ ;
                count1 = 1;
            }
        }
        if (ans_length < j - i + 1) {
            ans_length = j - i + 1;
            ans_start = i;
            ans_end = j;
        }
    }
    for (i = ans_start;i <= ans_end;i++)
        cout<<a[i]<<' ';
    return 0;
}


答案
第1空:j - 1
第2空:cur1
第3空:count1--
第4空:count2--
第5空:cur1 = a[j]

题目信息

题号:6607
题型:填空题
难度:普通