双指针 06

LeetCode 80

原题链接

HashMap

public int removeDuplicates(int[] nums) {
    Map map = new HashMap();
    int i = 0;
    for (int num : nums) {
        int count = (int) map.getOrDefault(num, 0) + 1;
        map.put(num, count);
        if (count <= 2) {
            nums[i++] = num;
        }
    }
    return i;
}

双指针

  • 用了官方的思路
官方思路
class Solution {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        if (n <= 2) {
            return n;
        }
        int slow = 2, fast = 2;
        while (fast < n) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}

你可能感兴趣的:(双指针 06)