LeetCode OJ 之 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 in place with constant memory.

不能使用其他的数组存储,必须在常数内存里完成,即空间复杂度为O(1)

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

Your function should return length = 2, and A is now [1,2].

代码1:

class Solution {
public:
    int removeDuplicates(int A[], int n) 
    {
        if(n == 0)
        return 0;
        int new_len=0;
        for(int i=1;i<n;i++)
        {
            //法一
            while(A[i] == A[new_len] && i < n)//循环结束条件,遇到不相等的数,或者到达数组末尾
                i++;
            if(i < n)   //如果还未到达末尾,则把不重复的数赋给A[new_len];
            A[++new_len] = A[i];
            //法二
            //if (A[i] != A[new_len])
            //    A[++new_len] = A[i];

        }
        return new_len+1;//注意上面的new_len是下标,要返回的数是个数,因此要+1
    }
};

代码2:

class Solution {
public:
    int removeDuplicates(int A[], int n) 
    {
        return distance(A, unique(A, A + n));//直接使STL
    }
};

代码3:

class Solution {
public:
    int removeDuplicates(int A[], int n) 
    {
        if(n < 2 )
    		return n;
    	int result = 1;
    	for(int i = 1 ; i < n ; i++)
    	{
    	    //if 执行完后result向后移动一个,之后A[i]和result之前的一位相比较
    	    //如果和之前的相同,则i++,如果不同,则把A[i]赋给当前result,然后result再加1位
    	    //这里的1代表只能出现一次,如果改为2,则意味着相同的数可以出现2次,改为n,意味着可以出现n次
    		if(A[i] != A[result - 1])
    			A[result++] = A[i];
    	}
    	return result;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值