Remove Duplicates from Sorted Array

VS的Format code

1.初阶。

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 A = [1,1,2],

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


2.进阶。

Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]


对于初阶。

思路1,从第二个数字开始遍历数组,只有和前一个数字不一样时,才放入数组。

思路2,使用stl. unique函数可以去除掉相邻的重复数字,distance可以返回数组的长度。

/* 思路1:
class Solution{
public:
	int removeDuplicates(int A[],int n){
		if(n == 0)return 0;
		int index = 0;
		for(int i = 1;i < n; i++){
			if(A[index] != A[i])
				A[++index] = A[i];
		}
		return index + 1;
	}
};

//思路2
class Solution{
public:
	int removeDuplicates(int A[],int n){
		return distance(A,unique(A,A+n));
	}
};


对于进阶。

思路1,因为允许一个重复的,并且数组本身是排好序的。那么只要从第三个数字开始遍历,只有和前两个数字不一样时,才放入数组。

注意:这里的比较A[i] != A[index - 2],不能写成A[i] != A[i-2].考虑a[] = {1,1,1,2,2,3,4,5,6};


最后一个1需要skip掉,此时index不变,而指向下一个数组元素,也就是第一个2。

处理第一个2时,a[i-2]=1,a[i] != a[i-2];index++,i++。此时a[2]被赋予了2.

处理第二个2时,a[i-2] = a[i],因为处理第一次2的时候,a[2]被赋值成了2.所以第二个2被skip了,这是不对的。

所以我们的比较应该A[i] != A[index - 2]。这个Index是新的数组的下标。

思路2,遍历数组,如果一个数字和前后的数字都相等,则抛弃,否则放入数组。

/* 思路1
class Solution{
public:
	int removeDuplicates2(int A[],int n){
		if(n <= 2)return n;
		int index = 2;

		for(int i= 2;i < n; i++){
			if(A[i] != A[index - 2])
				A[index++] = A[i];
		}
		return index;
	}
};
*/

//思路2
class Solution{
public:
	int removeDuplicates2(int A[],int n){
		int index = 0;
		for(int i = 0;i < n;i ++){
			if(i >0 && i< n - 1 && A[i] == A[i -1] && A[i] == A[i + 1])
				continue;
			A[index++] = A[i];
		}
		return index;
	}
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值