The original link
Given a sorted array, you need to remove duplicate elements in place so that each element appears only once, returning the new length of the removed array. Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.Copy the code
Example 1:
Given the array nums = [1,1,2], the function should return a new length of 2, and the first two elements of the original array nums are changed to 1,2. You don't need to worry about the element after the new length in the array.Copy the code
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], the function should return a new length of 5, and the first five elements of the original nums array are modified to 0,1, 2,3, 4. You don't need to worry about the element after the new length in the array.Copy the code
How fast a pointer
public static int removeDuplicates(int[] nums) { int slow = 0, fast = 1; // Stop while (fast < nums.length) {if (nums[slow]! = nums[fast]) {// slow moves one slow++; // If (slow! = fast) { nums[slow] = nums[fast]; }} // each loop fast pointer moves one space fast++; } return slow + 1; }Copy the code