Duplicates in a sorted java array

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

    Since this seems to be homework I don't want to give you the exact code, but here's what to do:

    • Do a first run through of the array to see how many duplicates there are
    • Create a new array of size (oldSize - duplicates)
    • Do another run through of the array to put the unique values in the new array

    Since the array is sorted, you can just check if array[n] == array[n+1]. If not, then it isn't a duplicate. Be careful about your array bounds when checking n+1.

    edit: because this involves two run throughs it will run in O(2n) -> O(n) time.

提交回复
热议问题