codeforces 解题报告 978A. Remove Duplicates 模拟

http://codeforces.com/contest/978/problem/A

解题思路:

1.删掉重复的元素,只留下序列中不重复的最右边的元素

2.逆向搜一遍,把第一次遇到的元素入栈

3.依次出栈就是答案

import java.util.*;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] ele = new int[100];
        for(int i = 1;i <= n;i++) {
            ele[i] = sc.nextInt();
        }

        Stack<Integer> s = new Stack<>();
        for(int i = n;i >= 1;i--) {
            if(s.contains(ele[i]))            //出现过的跳过
                continue;
            else
                s.push(ele[i]);               //没出现过的入栈
        }

        System.out.println(s.size());
        while (!s.empty()) {
            System.out.print(s.peek() + " ");
            s.pop();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/a912952381/article/details/81062341