Java 给定一个无序的整数流,保持顺序,但删除数组中只出现一次的元素
我的解决方案:Java 给定一个无序的整数流,保持顺序,但删除数组中只出现一次的元素,java,arrays,algorithm,hashmap,Java,Arrays,Algorithm,Hashmap,我的解决方案: public class removeUniqueElements { public static Integer[] removeUnique(int[] arr){ Map<Integer,Integer> output = new HashMap<Integer,Integer>(); List<Integer> result = new ArrayList<Integer>();
public class removeUniqueElements {
public static Integer[] removeUnique(int[] arr){
Map<Integer,Integer> output = new HashMap<Integer,Integer>();
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<arr.length;i++){
if(output.containsKey(arr[i])){
int count = output.get(arr[i]);
count = count+1;
output.put(arr[i],count);
}
else
{
output.put(arr[i],1);
}
}
for(int i=0;i<arr.length;i++){
if(output.get(arr[i])!=1){
result.add(arr[i]);
}
}
return result.toArray(new Integer[result.size()]);
}
public static void main(String[] args){
int[] array = {1,2,3,4,2,3,4};
Integer[] result = removeUnique(array);
System.out.println(Arrays.toString(result));
}
}
时间复杂性:On
空间复杂性:论
有没有其他方法可以降低空间复杂度?请提供帮助。为了获得更好的性能,请使用Map,这样您就可以简单地更新映射的计数器,而不是每次递增计数器时都装箱一个新值。这也将减少产生的垃圾量,这可以被认为是内存占用的减少,即使从技术上讲不是这样 为了减少内存占用,请不要使用列表或整数[]。将所有值装箱到整数中会产生大量的对象开销,并且首先创建一个列表,然后创建最终数组,这意味着要消耗2倍的引用数 相反,一旦构建了映射,计算要删除的值的数量,然后直接创建结果数组并填充它。没有装箱,也没有在列表上浪费空间 我将把这些改进留给您来调整代码。您可以使用Java8:
Arrays.stream(arr).collect(Collectors.groupingBy(Function.identity()).
entrySet().stream().filter(e -> e.getValue().size() != 1).
map(e -> e.getValue()).toArray(int[]::new);
你需要进一步澄清。时间复杂性?空间复杂性?开?我从来没有听说过X数组被称为X流。你确定你正确地解释了你的作业吗?这个问题看起来像是复制到:。@DevilsHnd否,你提供的链接会将示例1,2,3,4,2,3,4转化为1,2,3,4,删除重复项,虽然这个赋值是为了产生2,3,4,2,3,4个只发生一次的移除值。有一种方法可以在空间复杂度O1中解决这个问题,但时间复杂度达到n平方。这就是您要问的吗?此解决方案不会改善上的空间复杂性。然而,从Java的角度来看,这里介绍了许多优秀的概念。它减少了内存占用,但不降低复杂性。它仍然与输入的大小成线性关系,只是一条更平坦的曲线。