刪除陣列中重複元素 (使用stl::set)
阿新 • • 發佈:2019-01-05
/*
*程式作用刪除數中重複的元素,先使用set 遍歷一次陣列,然後在使用兩個指標,以及set查重,
*去重複之後使用0填補多餘空間
*複雜度 O(NlogN)
*空間複雜度 O(N)
*程式作用刪除數中重複的元素,先使用set 遍歷一次陣列,然後在使用兩個指標,以及set查重,
*去重複之後使用0填補多餘空間
*複雜度 O(NlogN)
*空間複雜度 O(N)
*/
以下是程式執行結果:#include<iostream> #include<set> using namespace std; void delete_over_arry(int *a,int len); void print(int *a ,int len); int main() { int p[]={1,1,2,5,3,7,3,4,8,2,1,3,9,1}; print(p,sizeof(p)/sizeof(int)); delete_over_arry( p,sizeof(p)/sizeof(int)); print(p,sizeof(p)/sizeof(int)); return 0; } void print(int *a ,int len) { for(int i=0;i<len;i++) cout<<a[i]; cout<<endl; } void delete_over_arry(int *a,int len) { set<int> temp_set; int *set_p=a+1; int *new_p=a+1; int count=0; temp_set.insert(a[0]); for(int i=1;i<len;i++) { if(temp_set.count(*set_p)) { set_p++; count++; } else { temp_set.insert(*set_p); *new_p++=*set_p++; } } for(int i=0;i<count;i++) *new_p++=0; }
[tr[email protected] code_test]$ g++ -o delete_overarray delete_overarray.cpp
[[email protected] code_test]$ ./delete_overarray
11253734821391
12537489000000