从大型未排序数组中删除重复项并保持顺序

问题描述:

我有一个未排序的整数数组,其值的范围从Integer.MIN_VALUE到Integer.MAX_VALUE.数组中可以有任何整数的多个重复项. 我需要返回一个删除所有重复项的数组,并保持元素顺序.

I have an unsorted array of integers where the value is ranging from Integer.MIN_VALUE to Integer.MAX_VALUE. There can be multiple duplicates of any integer in the array. I need to return an array with all duplicates removed and also maintain the order of elements.

示例:

int[] input = {7,8,7,1,9,0,9,1,2,8}

输出应为{7,8,1,9,0,2}

output should be {7,8,1,9,0,2}

我知道可以使用LinkedHashSet解决此问题,但我需要一个不占用大量缓冲区空间的解决方案.

I know this problem can be solved using LinkedHashSet but I need a solution which doesn't involve significant buffer space.

您可以使用Java 8数组stream.distinct()方法从数组中获取不同的值,并且仅保留输入顺序

You can use java 8 Arrays stream.distinct() method to get distinct values from array and it will remain the input order only

public static void main(String[] args) {
    int[] input = {7,8,7,1,9,0,9,1,2,8};
    int[] output = Arrays.stream(input).distinct().toArray();
    System.out.println(Arrays.toString(output)); //[7, 8, 1, 9, 0, 2]
}