LeetCode题解 -- 双指针(26)

Remove Duplicates from Sorted Array

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.

时间复杂度:O(n)
空间复杂度:O(1)

和 27题方法类似

    public int removeDuplicates(int[] nums) {
        int length = nums.length;
        if(length <= 1)
            return length;

        int temp = nums[0];
        int cur = 1;
        for(int i = 1;i < length;i++){
            if(nums[i] != temp){
                temp = nums[i];
                nums[cur++] = nums[i];
            }
        }

        return cur;
    }
发布了30 篇原创文章 · 获赞 0 · 访问量 873

猜你喜欢

转载自blog.csdn.net/fantow/article/details/104694960