Topic description
Given an ordered array, remove the repeating element from the array, leaving only a duplicate element and returning the new array length.
Requirements:
Do not assign extra space to the array, you must use the constant memory size for the in-situ operation.
For example:
To the array of a=[1,1,2], your function calls must return the length length=2, and a now becomes [1,2].
Input
An array of sorts, such as [1,1,2].
Output
Returns the new length of the array, such as length=2.
Fast and Fast pointer method
Sets the fast pointer to traverse the array, and the slow pointer points to the next digit of the element that does not repeat.
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 Demo:
Extended
Removes a repeating element from a sorted array and retains 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];< c8/>}
} return
index;
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.