LeetCode26:Remove Duplicates from Sorted Array

问题描述:
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.

思路:设两个指针,一个用作遍历,一个用来确定最近的不一样的数字的位置(称为该位置)。如果下一个数字与该位置相同,则啥也不干,继续遍历下一个,若不同,则把这个数字交换到该位置+1的位置。

题目不难,代码一遍过,直接上:

class Solution {
    public int removeDuplicates(int[] nums) {
        int length = 1;
        int temp;
        int the_nearest_available_storage = 0;
        for (int i=1; i<nums.length; i++){
            if (nums[i] != nums[the_nearest_available_storage]){
                length++;
                the_nearest_available_storage++;
                //swap nums[the_nearest_available_storage] and nums[i]
                temp = nums[the_nearest_available_storage];
                nums[the_nearest_available_storage] = nums[i];
                nums[i] = temp;
            }
        }
        return length;
    }
}

时间复杂度分析:O(n)

有一点需要强调的,数组从第二个元素(index1)开始遍历的,因为第一个元素本身有序且特别,所以起始的length=1.

5月4日二刷,用了相似的方法:稍有不同。先排除不用运算的情况,即数组长度为0和长度为1. 同样是设两个指针,低位指针用来确定下一个数应该在的位置,高位指针用来遍历。如果两个指针差距大于1,则说明中间的空当应该补进去,否则两个指针齐头并进,直到高位指针达到length(即所有的元素都被安排过了)。

代码如下:


class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length<=1) return nums.length;
        int pointer1=0;
        int pointer2=1;
        int temp;
        while(pointer2<nums.length){
            if (nums[pointer1] == nums[pointer2]){
                pointer2++;
            }
            else{
                if (pointer2-pointer1>1){
                    //swap nums[pointer1+1] and nums[pointer2]
                    temp=nums[pointer2];
                    nums[pointer2] = nums[pointer1+1];
                    nums[pointer1+1] = temp;
                }
                pointer1++;
                pointer2++;
            }
        }
        return pointer1+1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值