且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用 Set 的情况下有效地从数组中删除重复项

更新时间:2023-01-11 07:42:46

由于这个问题还是很受关注,所以我决定复制来自 Code Review.SE 的这个答案:

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?:

  • 使用 quicksort 对无序数组进行排序.快速排序要快得多比冒泡排序(我知道,你不是排序,而是你的算法follow 几乎和冒泡排序一样来遍历数组).

  • 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).

然后开始删除重复项(重复值将在每个其他).在 for 循环中,您可以有两个索引:source目的地.(在每个循环中,您将 source 复制到 destination 除非它们是相同的,并且都加 1).每次你找到一个复制您的增量源(并且不执行复制).@摩根诺

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