原题:

https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&envId=top-interview-150

解析:

  1. 两个重复元素,需要找到要替换的位置last,和可替换的位置fast,因此双指针是必要的。

  2. 哪里是要替换的位置?第三个值和第一个值相同时,需要替换。

  3. 哪里是可替换的位置?第一个值和fast的值不相同时,替换第三个值。

这么简单的思路为啥想不到?

题解:

    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) {
            return nums.length;
        }
        int last = 2;
        int fast = 2;
        while (fast < nums.length) {
            if (nums[last-2] != nums[fast]) {
                nums[last]= nums[fast];
                last++;
            }
            fast++;
        }
        return last ;
    }