Duplicates in a sorted java array

前端 未结 5 1992
傲寒
傲寒 2021-01-07 12:31

I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers

5条回答
  •  佛祖请我去吃肉
    2021-01-07 12:42

    Tested and works (assuming the array is ordered already)

    public static int[] noDups(int[] myArray) { 
    
        int dups = 0; // represents number of duplicate numbers
    
        for (int i = 1; i < myArray.length; i++) 
        {
            // if number in array after current number in array is the same
            if (myArray[i] == myArray[i - 1])
                dups++; // add one to number of duplicates
        }
    
        // create return array (with no duplicates) 
        // and subtract the number of duplicates from the original size (no NPEs)
        int[] returnArray = new int[myArray.length - dups];
    
        returnArray[0] = myArray[0]; // set the first positions equal to each other
                                     // because it's not iterated over in the loop
    
        int count = 1; // element count for the return array
    
        for (int i = 1; i < myArray.length; i++)
        {
            // if current number in original array is not the same as the one before
            if (myArray[i] != myArray[i-1]) 
            {
               returnArray[count] = myArray[i]; // add the number to the return array
               count++; // continue to next element in the return array
            }
        }
    
        return returnArray; // return the ordered, unique array
    }
    

    My previous answer to this problem with used an Integer List.

提交回复
热议问题