Duplicates in a sorted java array

前端 未结 5 1946
傲寒
傲寒 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:57

    public static int[] findDups(int[] myArray) {
        int numOfDups = 0;
        for (int i = 0; i < myArray.length-1; i++) {
            if (myArray[i] == myArray[i+1]) {
                numOfDups++;
            }
        }
        int[] noDupArray = new int[myArray.length-numOfDups];
        int last = 0;
        int x = 0;
        for (int i = 0; i < myArray.length; i++) {
            if(last!=myArray[i]) {
                last = myArray[i];
                noDupArray[x++] = last;
            }
        }
        return noDupArray;
    }
    

提交回复
热议问题