删除数组中的重复项

251 阅读1分钟

删除数组中的重复项(Remove Duplicates from Sorted Array)

给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

解法:

    public static int removeDuplicates(int[] nums) {

        if (nums == null || nums.length == 0) {
            return 0;
        }
        int p = 0;
        int q = 1;
        while (q < nums.length) {
            if (nums[p] != nums[q]) {
                nums[p+1] = nums[q];
                p++;
            }
            q++;
        }

        return p + 1;
        //简化后,就是官网的做法
//        if (nums.length == 0) {
//            return 0;
//        }
//        int i = 0;
//        for (int j = 1; j < nums.length; j++) {
//            i++;
//            nums[i] = nums[j];
//        }
//        return i + 1;
    }

图解思路:

1.png

还有一个小优化,如果当数组中没有重复元素时,每次比较时 nums[p] 都不等于 nums[q],因此就会将 q 指向的元素原地复制一遍,这个操作其实是不必要的。

因此我们可以添加一个小判断,当 q - p > 1 时,才进行复制。

    public static int removeDuplicates(int[] nums) {

        if (nums == null || nums.length == 0) {
            return 0;
        }
        int p = 0;
        int q = 1;
        while (q < nums.length) {
            if (nums[p] != nums[q]) {
            		if(q - p > 1){
                	nums[p+1] = nums[q];
                }
                p++;
            }
            q++;
        }

        return p + 1;
    }