LeetCode 80. Remove duplicates in ordered array II

Article directory

1. Title

  You are given an ordered array nums, please delete the repeated elements in place , so that the elements that appear more than twice only appear twice, and return the new length of the array after deletion.

  Do not use extra array space, you must modify the input array in-place and O(1)do it while using extra space.

illustrate:

Why is the returned value an integer but the output answer is an array?

Please note that the input array is passed by "reference" , which means that modifications to the input array in the function are visible to the caller.

You can imagine the internal operation as follows:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

  Click here to jump to the question .

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 length = 5, and the first five of the original array elements were modified to 1, 1, 2, 2, 3. Elements in the array beyond the new length do not need to be considered.

Example 2:

Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3]
Explanation: The function should return new The length is length = 7, and the first five elements of the original array are modified to 0, 0, 1, 1, 2, 3, 3. Elements in the array beyond the new length do not need to be considered.

hint:

  • 1 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • numsSorted in ascending order

2. Java problem solving

  Use double pointers iand to point to jthe iend of the modified array jto traverse each element of the array. At the same time, use to cntrecord the current number of repeated elements, each time jmoving to the next bit cnt + 1. Compare nums[j]and nums[j - 1], if different, reset cntto 1, if they are the same, judge cntwhether > 2, if so, do not process, continue to jthe next digit, if not, update nums[i]and iadvance one digit. The specific implementation is as follows, with slight changes to the code logic to improve efficiency:

class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    
        int i = 1, cnt = 1;
        for (int j = 1; j < nums.length; j++) {
    
    
            cnt++; // 更新记录 + 1
            if (nums[j] == nums[j - 1] && cnt > 2) continue; // 如果 cnt > 2,则 j 继续前进,不作处理
            if (nums[j] != nums[j - 1]) cnt = 1;             // 遇到第一个不同的数,更新记录
            nums[i++] = nums[j]; // 赋值,i 前进一位
        }

        return i;
    }
}
  • Time: 0 ms, beats 100.00% of users using Java
  • Memory: 41.47 MB, beats 73.03% of users using Java

Guess you like

Origin blog.csdn.net/zheliku/article/details/133201456