問題:去除數組中重複的元素。
輸入:
2, 7, 3, 7, 2, 9, 9, 3
輸出:
2, 7, 3, 9
思路:
1、利用數組
準備一個額外空間的數組A,遍歷輸入數組中的元素,每個元素都去數組A中遍歷,A中存在則不管,不存在就將該元素放入數組A。
2、利用ADT
利用語言自身所帶的紅黑底層結構的容器,如Java的TreeSet以及TreeMap,C++的unordered_set,set。準備一個這樣的結構,遍歷輸入數組,往容器中插入,遍歷完成後,容器中的元素就是去重後的元素。這個方案的時間複雜度爲O(nlogn),空間複雜度爲O(n)。
利用hash結構,hashtable。
遍歷每個元素,放入hash結構。這個方案的缺陷在於,隨着輸入規模的增大,最後hash結構會退化,導致效率下降。
拓展:記錄每個元素出現的次數
3、引入排序
調用語言庫排序算法
將排序手段看作一個ADT。
先將輸入的數組S排序。再引入兩個int變量L和R,分別指向排序後的起始下標。
R向右移動(自增),判斷S[R]和S[L]是否相等,如果相等,R繼續向右移動(自增)。
S[R]與S[L]不等的時候,R - L 就是S[L]元素出現的次數。打印S[L]及 R-L 的值。L再移動到R的位置。圖示如下:
C++示例代碼:
#ifndef SOLUTION_HPP
#define SOLUTION_HPP
#include <vector>
#include <algorithm>
using namespace std;
class Solution{
public:
static void unique(vector<int>& vec)
{
if(vec.size() == 0)
return;
std::sort(vec.begin(), vec.end());
unsigned int Left = 0, Right = 0;
for(; Left < vec.size(); Left = Right)
{
for(Right = Left + 1; Right < vec.size(); ++Right)
{
if(vec[Left] != vec[Right])
{
break;
}
}
cout << vec[Left] << " : " << Right - Left << endl;
}
}
};
#endif // SOLUTION_HPP
調用示例:
#include <iostream>
/*#include "LinuxList.h"*/
#include "solution.hpp"
//#include "commondef.hpp"
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
//UNUSED(argc);
//UNUSED(argv);
cout << "Hello World!" << endl;
vector<int> list = {2, 7, 3, 7, 2, 9, 9, 3};
Solution::unique(list);
return 0;
}
最後這個方案,使用了標準庫的排序算法,時間複雜度O(n log n) 如果需要引入其他的容器來存結果的話,空間複雜度爲O(n)。
總結:
- 有時候將排序看作一種ADT手段也是一種。
- 善用語言標準庫提供的工具。