English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Description of the problem
Given a sorted array, remove the repeated elements from the array, keep only one repeated element, and return the new array length.
Requirements:
Do not allocate extra space for the array, you must use constant memory size for in-place operations.
For example:
Given the sorted array A=[1,1,2], and your function must return the length length=2, and A is now changed to [1,2].
Input
An already sorted array, for example, [1,1,2].
Output
Return the new length of the array, for example, length=2.
Two-pointer method
Set the fast pointer to traverse the array and the slow pointer to point to the next element of the non-repeated 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:
Expansion
Remove duplicate elements from the sorted array and retain 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; }
That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yell Tutorial more.
Statement: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not bear relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)