Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - How to delete all duplicate element from an array without using any library or collection

As the header said. I want to delete all duplicate element from an array without using any library or collection. I usually use Set or HashMap but it is not possible anymore in this case. I also thought about sort the array and check from the beginning to the end like

If(arr[i]==a[i+1])
delete arr[i]; i--;

Or maybe something like using 2 for loops. But they are not efficient enough. Are there any other more efficiently way to delete duplicates? Thank you!


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

1 Answer

0 votes
by (71.8m points)

If we sort the array, any duplication between the values will be close to each other. That way we can remove them

  int a[] = { 1,9,55,1,8,9,77,2,5,54,7,10,11 };
    Arrays.sort(a);
    int j = 0;
    for (int i = 0; i < a.length - 1; i++) {
        if (a[i] != a[i + 1]) {
            a[j] = a[i];
            j++;
        }
    }
    a[j] = a[a.length - 1];
 return a;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...