Question description
Given a sorted array, remove duplicate elements from the array, retain only one duplicate element, and return the new array length.
Require:
Don't allocate extra space to the array, you have to use the memory size of the constant to operate in place.
For example:
Given the array A=[1,1,2], your function call must return length=2, and A now becomes [1,2].
enter
A sorted array, for example [1,1,2].
Output
Returns the new length of the array, for example length=2.
Fast and Slow Pointer Method
Set the fast pointer to traverse the array, and the slow pointer to the next bit of the non-repeat element.
public static int removeDuplicates(int[] nums){ if (nums.length < 1) return nums.length; int slow = 1; for (int fast = 1; fast < nums.length; fast++) { if (nums[fast] != nums[slow - 1]) { nums[slow++] = nums[fast]; } } return slow;}Animation demonstration:
Extended
Removes duplicate elements from the sorted array, leaving the specified number of digits.
public static int removeDuplicatesN(int[] nums, int repeatN){ if (nums.length <= repeatN) return nums.length; int index = repeatN; for (int i = repeatN; i < nums.length; i++) { if (nums[i] != nums[index - repeatN]) { nums[index++] = nums[i]; } } return index;}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.