NetEase 2017 Spring Written Exam Real Questions Programming Question Collection - 4. Eliminate repeated elements

Question

Xiaoyi has a sequence of length n, Xiaoyi wants to remove the repeated elements in it, but Xiaoyi wants to keep the last appearing one for each element. Xiaoyi is in trouble, and I hope you can help him.
Input description: The
input consists of two lines:
the first line is sequence length n (1 ≤ n ≤ 50)
and the second line is n number sequence[i] (1 ≤ sequence[i] ≤ 1000), separated by spaces

Output description:
Output the sequence after eliminating duplicate elements, separated by spaces, with no spaces at the end of the line

Input example:
9
100 100 100 99 99 99 100 100 100

Example output:
99 100

Basic idea:
use Scanner to receive console input The
difficulty should be to keep the last sentence for each element
in the requirement: when the following situation occurs: 100 100 99 11 11 11, removing duplicate elements must be: 100 99 11
And if this happens: 100 100 100 99 99 99 100 100 100, in order to meet the requirement of retaining the last one for each element , 100 appears before and after the three 99s, and only the 100 after 99 can be retained. , that is, 99 100; it is
only necessary to traverse the given array from the back to the front to meet the requirement of retaining the last appearing one for each element, and use an ArrayList to save the collection after merging the repeated elements. Determine whether the element already exists in the set, and add it to the set if it does not exist.
At the end of the traversal, the collection should be output in reverse order , because the traversal of the target array is from back to front during traversal, and the order of adding to the collection is also from back to front, and the output should be output from front to back.

The java code is as follows:

public class GetOffer4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        sc.nextLine();
        String str = sc.nextLine();
        String[] arr = str.split(" ");
        int k = 0;
        int[] newArr = new int[size];
        for (String value : arr) {
            newArr[k++] = Integer.valueOf(value);
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        // 从后往前遍历,如果重复不添加,
        for (int i = newArr.length - 1; i >= 0; i--) {
            if (!list.contains(newArr[i])) {
                list.add(newArr[i]);
            }
        }
        // 倒序遍历集合
        for (int i = list.size() - 1; i >= 0; i--) {
            if (i == 0) {
                System.out.print(list.get(i));
            } else {
                System.out.print(list.get(i) + " ");
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326270526&siteId=291194637