How to remove duplicate elements sorted array (speed pointer)

 

 

Description link

How to remove duplicate elements in an ordered array

We know that for arrays, in the tail insert, delete elements are relatively efficient, time complexity is O (1), but if inserted at the beginning or in the middle, remove elements, will involve moving data, the time complexity is O (N), less efficient.

So for the general problem of dealing with an array of algorithms, we want only the elements of the array end of the operation as possible, to avoid the extra time complexity.

This article talk about how to go heavy on a sorted array, look under the topic:

Obviously, since the array is already sorted, so we must duplicate elements together, they are not difficult to find, but if you find a duplicate every element immediately delete it, delete operation is in the middle of the array, the overall time complexity is to reach O (N ^ 2). And the subject requires us to place editing, which means that aid can not be used array space complexity gotta be O (1).

In fact, for an array of issues related to the algorithm, there is a common trick: Try to avoid delete elements in the middle, I wanted a way to change this element to the last to go. In this case, the final element to be deleted in the array are dragging tail, one by one, pop out on the line, the time complexity of each operation will be reduced to O (1) a.

According to this idea of ​​it, but can be derived from a common way to solve similar needs: a double pointer skills. Specifically, it can be a pointer speed.

We make slow pointer  slow go left behind, fast hands  fast walking in front of Pathfinder, do not find a duplicate elements to tell  slow and make  slow further before. So that when  fast the pointer to traverse the full array  nums after, nums[0..slow] just do not repeat the elements, all the elements are then repeated elements.

int removeDuplicates(int[] nums) {
    int n = nums.length;
    if (n == 0) return 0; int slow = 0, fast = 1; while (fast < n) { if (nums[fast] != nums[slow]) { slow++; // 维护 nums[0..slow] 无重复 nums[slow] = nums[fast]; } fast++; } // 长度为索引 + 1 return slow + 1; }

Look at the process of execution of the algorithm:

Then a simple extension of that, if you give an ordered list, how to re-do? In fact, and arrays are exactly the same, the only difference is the array assignment operator pointer only becomes operational:

ListNode deleteDuplicates(ListNode head) {
    if (head == null) return null; ListNode slow = head, fast = head.next; while (fast != null) { if (fast.val != slow.val) { // nums[slow] = nums[fast]; slow.next = fast; // slow++; slow = slow.next; } // fast++ fast = fast.next; } // 断开与后面重复元素的连接 slow.next = null; return head; }

Guess you like

Origin www.cnblogs.com/-wenli/p/12512870.html