leetcode中Remove Duplicates from Sorted Array II 问题解决
问题描述
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].
简单的说就是将数组中连续的大于等于2个的多余的去掉
1,1,1,1,2,2,1变为1,1,2,2,1,大小为5
明白了问题下面贴出代码
class Solution {
public:
int removeDuplicates(int A[], int n) {
int len=2,temp=2;
if(n<=2) return n;
while(temp < n){
if(A[temp] != A[len-2]){
//先执行A[len] = A[temp],然后再执行len++
A[len++] = A[temp];
}
temp++;
}
return len;
}
};
一定要注意的是上面中是先赋值在len++,这个的作用是修改A数组
贴出完整的C代码
#include <stdio.h>
int removeDuplicates(int A[], int n) {
int len=2,temp=2;
if(n<=2) return n;
while(temp < n){
if(A[temp] != A[len-2]){
A[len++] = A[temp];
}
temp++;
}
return len;
}
int main(int argc, const char * argv[])
{
int A[] = {1,1,1,2,2,3,1};
int j = removeDuplicates(A,7);
printf("%d",j);
return 0;
}