从整数数组中删除重复项 [英] Remove duplicates from integer array

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

问题描述

我在编码时遇到问题:

编写一个名为 removeDuplicates 的静态方法,该方法将一个整数数组作为输入,并返回一个删除所有重复项的新整数数组.例如,如果输入数组具有元素 {4, 3, 3, 4, 5, 2, 4} 则结果数组应该是 {4, 3, 5, 2}

Write a static method named removeDuplicates that takes as input an array of integers and returns as a result a new array of integers with all duplicates removed. For example, if the input array has the elements {4, 3, 3, 4, 5, 2, 4} the resulting array should be {4, 3, 5, 2}

这是我到目前为止所做的

Here's what I have done so far

public static int[] removeDuplicates(int []s){
    int [] k = new int[s.length];
    k[0]=s[0];
    int m =1;
    for(int i=1;i<s.length;++i){
        if(s[i]!=s[i-1]){
            k[m]=s[i];
            ++m;
        }//endIF
    }//endFori
    return k;
}//endMethod

推荐答案

要保留排序并删除整数数组中的重复项,您可以尝试:

To Preserve the ordering and to remove duplicates in the integer array, you can try this:

public void removeDupInIntArray(int[] ints){
    Set<Integer> setString = new LinkedHashSet<Integer>();
    for(int i=0;i<ints.length;i++){
        setString.add(ints[i]);
    }
    System.out.println(setString);
}

希望这会有所帮助.

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

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