Remove Duplicates from Sorted Array

题目:
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 by **modifying the input array in-place with O(1) extra memory.

Example:

Given 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.

分析:
maintain 2个index i 和 j, j > i
i和i的左边的所有元素都是没有duplicates的
从j = i+1开始往右扫描,如果nums[j]不等于nums[i], 那么就找到了一个非duplicate的元素,把这个元素放置在nums[i+1],并且让i自增1.如果nums[j]等于nums[i], 则使j自增1,跳过这个duplicate的元素

    public int removeDuplicates(int[] nums) {
        if(nums.length <= 1) return nums.length;
        int n = nums.length, size = 1, j = 1;
        while(j < n) {
            if(nums[j] != nums[size - 1]) {
                nums[size++] = nums[j];
            }
            j++;
        }
        return size;
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容