题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Runtimes:37ms
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、分析
第一个想法是从后面扫描,再搬运覆盖掉重复的数字,时间复杂度O(n^2),空间复杂度O(1),时间上不划算;
第二个想法是重新开个数组,将不重复的元素帮过去,最后返回新数组,时间复杂度O(n),空间复杂度O(n),空间上不允许;
第三个想法是两个指针i = 0、j = 1,j从头开始扫描,扫到不重复的元素,A[i] = A[j],i++, j++, 循环往复。
3、小结
从时间上、空间上压缩,会找到一个不错的方法。
4、实现
实现方案一:
class Solution {
public:
int removeDuplicates(int A[], int n) {
for(int i = n - 1; i >0; )
{
int j = i - 1;
while(j >= 0 && A[j] == A[i])
{
j--;
}
if(j < i - 1)
{
for(int k = j + 1, m = i; m < n; k++, m++)
{
A[k] = A[m];
}
n -= (i - j - 1);
}
i = j;
}
return n;
}
};
实现方案二:
class Solution {
public:
int removeDuplicates(int A[], int n) {
int B[5000], m = 0;
for(int i = 0; i < n; )
{
B[m++] = A[i];
int j = i + 1;
while(j < n && A[j] == A[i])
{
j++;
}
i = j;
}
A = B;
return m;
}
};
实现方案三:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n < 2)
return n;
int i = 0;
int j = 1;
while(j < n)
{
if(A[i] == A[j])
{
j++;
}else{
i++;
A[i] = A[j];
j++;
}
}
return i + 1;
}
};
5、反思
从这篇文章得到启发,有时候自己的思路还是有点笨拙,加油!
文章链接:http://www.programcreek.com/2013/01/leetcode-remove-duplicates-from-sorted-array-java/