How to efficiently remove duplicates from an array without using Set

后端 未结 30 2457
情深已故
情深已故 2020-11-22 07:29

I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long ti

30条回答
  •  盖世英雄少女心
    2020-11-22 07:46

    Since this question is still getting a lot of attention, I decided to answer it by copying this answer from Code Review.SE:

    You're following the same philosophy as the bubble sort, which is very, very, very slow. Have you tried this?:

    • Sort your unordered array with quicksort. Quicksort is much faster than bubble sort (I know, you are not sorting, but the algorithm you follow is almost the same as bubble sort to traverse the array).

    • Then start removing duplicates (repeated values will be next to each other). In a for loop you could have two indices: source and destination. (On each loop you copy source to destination unless they are the same, and increment both by 1). Every time you find a duplicate you increment source (and don't perform the copy). @morgano

提交回复
热议问题