Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

java - Remove duplicates from integer array

I having a problem with coding this:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...