This is the 12th day of my participation in the First Challenge 2022
leetcode Delete duplicate item II from an ordered array
Give you an ordered array nums, ask you to delete duplicate elements in place, make each element appear at most twice, return the new length of the deleted array.
Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.
Example 1:
Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3] Explanation: The function should return the new length = 5, and the first five elements of the original array are modified to 1,1,2,2,3. You don't need to worry about the element after the new length in the array.Copy the code
Example 2:
Input: nums =,0,1,1,1,1,2,3,3 [0] output: 7, nums =,0,1,1,2,3,3 [0] interpretation: The function should return the new length = 7, and the first five elements of the original array are modified to 0, 0, 1, 1, 2, 3, 3. You don't need to worry about the element after the new length in the array.Copy the code
Problem solving: To in situ delete the array elements, nor to really delete the repeated elements of the array, just need to move all ordered not repeat an array of the most left side, there is the back part of the element of an array, just need to return to the front part of the number of the elements behind the situation don’t tube, therefore, as long as to find a way to find out all not repeating elements in the array, You can arrange them from left to right and then the left end of the array. However, in the case of an ordered array, duplicate elements can appear at most twice, instead of only keeping one digit. Therefore, only when there are more than two duplicate elements, the remaining elements need to be deleted. If there are no more than two duplicates, the element should be kept and moved to the specified position. If there are no more than two duplicates, the element needs to be deleted. The slow pointer indicates the length of the array to be processed, and the fast pointer indicates the length of the array to be processed. The initial value of the double Pointers to slow and fast is set to 2, since arrays of length less than or equal to 2 are not processed. If nums[fast] = nums[slow-2], the current element should not be retained. If nums[fast] = nums[slow-2], the current element should not be retained. Nums [slow – 2]=nums[slow – 1]=nums[fast]
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
if (len <= 2) {
return len;
}
int slow = 2;
int fast = 2;
while (fast < len) {
if (nums[slow - 2] != nums[fast]) {
nums[slow] = nums[fast];
slow++;
}
fast++;
}
returnslow; }}Copy the code