[英]Is it possible to remove duplicates from an unsorted array in O(n) time, O(1) space complexity, using the Floyd's tortoise and hare algorithm?
Is it possible to remove duplicates from an unsorted array in O(n) time, O(1) space complexity, using the Floyd's tortoise and hare algorithm?是否可以使用 Floyd 的龟兔算法在 O(n) 时间、O(1) 空间复杂度内从未排序的数组中删除重复项? Consider the array [3,1,3,4,2].
考虑数组 [3,1,3,4,2]。 After removing duplicates, the function "remove_dups" must return [3,1,4,2].
删除重复项后,function“remove_dups”必须返回 [3,1,4,2]。 Also, the function should work on negative integers in the array.
此外,function 应该适用于数组中的负整数。
Yes it is possible.对的,这是可能的。 The idea is to consider array items as linked list nodes.
这个想法是将数组项视为链表节点。 Any particular index is pointing to the value at that index.
任何特定索引都指向该索引处的值。
And you will see that there is loop in case of duplicate, two indexes will have same value, and they will form a cycle just like in the image given below.你会看到在重复的情况下存在循环,两个索引将具有相同的值,它们将形成一个循环,如下图所示。
Example:例子:
1->2->3->4->5->6->3 1->2->3->4->5->6->3
So we can find the entry point of cycle in the linked list and that will be our duplicate element.所以我们可以在链表中找到循环的入口点,这将是我们的重复元素。
Source: https://www.geeksforgeeks.org/find-duplicates-constant-array-elements-0-n-1-o1-space/资料来源: https://www.geeksforgeeks.org/find-duplicates-constant-array-elements-0-n-1-o1-space/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.