26. Remove Duplicates from Sorted Array

来源:互联网 发布:excel数据比对 编辑:程序博客网 时间:2024/06/15 16:05

Given a sorted array, 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 in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

该题的思路比较简单,就是统计一下重复数据的个数,该个数确定了后面的数字将要进行移动的位数,在移动的同时我们需要记录互不相同的数据个数,代码如下:

public int removeDuplicates(int[] nums) {
        // 特殊情况处理
        if(nums == null || nums.length == 0){
            return 0;
        }
        
        int countOfMove = 0, totalCount = 1;
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == nums[i - 1]){
                countOfMove++;
            }else{
                nums[i - countOfMove] = nums[i];
                totalCount++;
            }
        }
        return totalCount;
    }

最后我们可以进行一下优化,不用声明总的数据个数,我们只需要nums.length - countOfMove即可得到数组的长度

后来发现还有更加简洁的代码,值得学习,创建一个变量用来代表元素应该存储的位置,当发现相邻两个数不相同时,就将该值放置对应的位置上:

public int removeDuplicates(int[] nums) {
        // 特殊情况处理
        if(nums == null || nums.length == 0){
            return 0;
        }
        
        int position = 1;
        for(int i = 1; i < nums.length; i++){
            if(nums[i] != nums[i - 1]){
                nums[position++] = nums[i];
            }
        }
        return position;
    }

0 0