Removing Duplicates in an array in C

前端 未结 5 1420
醉酒成梦
醉酒成梦 2020-12-20 08:09

The question is a little complex. The problem here is to get rid of duplicates and save the unique elements of array into another array with their original sequence.

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 08:13

    As Thomas suggested in a comment, if each element of the array is guaranteed to be from a limited set of values (such as a char) you can achieve this in O(n) time.

    1. Keep an array of 256 bool (or int if your compiler doesn't support bool) or however many different discrete values could possibly be in the array. Initialize all the values to false.
    2. Scan the input array one-by-one.
    3. For each element, if the corresponding value in the bool array is false, add it to the output array and set the bool array value to true. Otherwise, do nothing.

提交回复
热议问题