从大型未排序数组中删除重复项并保持顺序 [英] Remove duplicates from a large unsorted array and maintain the order

查看:60
本文介绍了从大型未排序数组中删除重复项并保持顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未排序的整数数组,其值的范围从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]
}

这篇关于从大型未排序数组中删除重复项并保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆