How can I remove duplicate elements from a given array in java without using collections

后端 未结 10 818
逝去的感伤
逝去的感伤 2021-01-06 02:20

I have an array elements like this:

int arr[] = {1,1,2,2,3,3,4,4};

I want to remove the duplicate elements from. Searched on the internet

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 02:58

    Use below method:

    /*
     * Method to remove duplicates from array in Java, without using
     * Collection classes e.g. Set or ArrayList. Algorithm for this
     * method is simple, it first sort the array and then compare adjacent
     * objects, leaving out duplicates, which is already in the result.
     */
    public static int[] removeDuplicates(int[] numbersWithDuplicates) {
    
        // Sorting array to bring duplicates together      
        Arrays.sort(numbersWithDuplicates);     
    
        int[] result = new int[numbersWithDuplicates.length];
        int previous = numbersWithDuplicates[0];
        result[0] = previous;
    
        for (int i = 1; i < numbersWithDuplicates.length; i++) {
            int ch = numbersWithDuplicates[i];
    
            if (previous != ch) {
                result[i] = ch;
            }
            previous = ch;
        }
        return result;
    
    }
    

提交回复
热议问题