问题分析
对于已经排序的数组,我们可以定义两个指针slow, fast,我们假设数组的长度是大于等于2的,那么初始时slow指向数组的第0个元素,fast指向第1个元素。接着,移动fast指针,如果指针指向的值不同,那么把fast赋值给slow,fast继续移动,直至fast指向数组末尾。那么所有slow一共指向过的元素就是原数组中所有不同的元素。
然而,对于无序的数组,这个方法将不再适用。我们可以使用一个字典,来记录数组中每个元素出现的次数。如果是第一次出现,我们就保留,否则丢弃,这样得到的就是数组中所有不同的元素。
代码实现(C++)
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
void removeSameElements(vector<int> & list);
void removeOrderedSameElements(vector<int> & list);
ostream & operator<<(ostream & os, const vector<int> & list);
int main() {
vector<int> list = {3,9,1,6,3,6,9,1,2,7};
removeSameElements(list);
cout << list;
return 0;
}
ostream & operator<<(ostream & os ,const vector<int> & list) {
int i = 0;
cout << "{";
for (i = 0; i < list.size() - 1; ++i) {
cout << list[i] << ", ";
}
cout << list[i];
cout << "}" << endl;
return os;
}
void removeOrderedSameElements(vector<int> & list) {
if (list.size() < 2)
return;
// sort(list.begin(), list.end());
int slow = 0;
int fast = 1;
vector<int> ans;
ans.push_back(list[slow]);
while (fast < list.size() - 1) {
if (list[fast] != list[slow]) {
ans.push_back(list[fast]);
slow = fast;
// fast++;
}
fast++;
}
list = ans;
}
void removeSameElements(vector<int> & list) {
map<int,int> dict;
vector<int> ans;
for (int num: list) {
if (dict.count(num) == 0) {
dict[num] = 1;
ans.push_back(num);
}
}
list = ans;
}