LeetCode - 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:js文件在线格式化 编辑:程序博客网 时间:2024/05/18 02:58

方法一:

这一种方法是第一个想到的,因为题目中要求删除的是出现两次及其以上的元素,所以在思考的时候想到了使用HashMap来记录数组中每个元素出现的次数,对于出现次数大于2的元素就删除。删除的方法是由26. Remove Duplicates from Sorted Array的思路得来,使用两个指针,碰到重复>=两次的直接跳过,其余的向前移动的前一个指针指定的位置上

/* HashMap */public class Solution {    public int removeDuplicates(int[] nums) {        //extreme situation        if(nums == null) return 0;                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();                //init HashMap        for(int i = 0; i < nums.length; i++){            if(map.containsKey(nums[i])){                map.replace(nums[i], map.get(nums[i]) + 1);            }else{                map.put(nums[i], 1);            }        }                int index = 0;        for(int i = 1; i < nums.length; i++){            if(map.get(nums[i]) <= 2){                index++;                nums[index] = nums[i];            }else{                //update HashMap                map.replace(nums[i], map.get(nums[i]) - 1);            }        }                return index + 1;    }}

方法二:

方法一确实可以解决这个问题,但是这却忽略了题目中的一个非常重要的条件:sorted,所以方法一是通用的,无论对于排序过的还是没有排序的都可以使用。sorted这个条件说明了一个问题,那就是与某元素相同的元素只可能在它的周围。在删除数组中的重复元素时,我们需要比较的是某元素和index - 2位置的元素的大小,在这种方法中,如果遇到的元素并不是重复了>=2次,那么index就会与i一直保持同步并在每一次循环中+1,如果遇到的是重复多次的元素的前两次出现时也是如此,只有当第三次出现的时候,i和index - 2位置上的元素才会相等,此时i开始跳过并寻找下一个不想等的元素。这种方法是一个通用的方法,以后如果要删除重复n次的元素,也只要在这种方法上进行微调即可

/* Element Compare */public class Solution {    public int removeDuplicates(int[] nums) {        //extreme situation        if(nums == null) return 0;        if(nums.length < 2) return nums.length;                int index = 2;        for(int i = 2; i < nums.length; i++){            if(nums[i] != nums[index - 2]){                nums[index] = nums[i];                index++;            }        }        return index;    }}
知识点:

1. HashMap: get(key), put(key, value), replace(key, newValue);


0 0