给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用O(1)额外空间的条件下完成。
试卷: 浩鲸科技2019校招算法类笔试题
- 题目给定数组
有序
,于是相等
的元素一定紧挨在一起
- 我们可以
O(n)
的去重 - 输入格式反人类
#ifdef debug
#include <time.h>
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e6+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K, a[MAXN], sz;
int get_num(char* s, int& i) {
int tmp = 0;
for( ; s[i]!=']'; ) {
if(s[i] == ',') { i++; break; }
else {
tmp = tmp * 10 + (s[i]-'0');
i ++;
}
}
return tmp;
}
char buf[MAXN];
signed main() {
#ifdef debug
freopen("test.txt", "r", stdin);
clock_t stime = clock();
#endif
scanf("%s ", buf);
int i = 1, j;
while(buf[i] && buf[i]!=']') {
int p = get_num(buf, i);
a[++sz] = p;
}
// for(int i=1; i<=sz; i++) printf("[%d] ", a[i]);
// printf("\n");
for(i=2, j=1; i<=sz; i++) {
// show(a[i], a[i-1]);
if(a[i] == a[j]) continue ;
a[++j] = a[i];
}
// for(int i=1; i<=j; i++) show(a[i]);
printf("%d\n", j);
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}