c++ 實現向量去重操作


去重的時候要考慮線性表或鏈表是否是有序

     1.1.無序線性表   

     對於向量[1,5,3,7,2,4,7,3], 從頭開始掃描vector內的元素, 對於表中r處的元素a[r], 檢查數組0至r-1區間內是否存在與a[r]重復的元素, 如果存在就刪除,否則r++

void deduplicate(vector<int> a){
    int len = a.size(), r = 0;
    vector<int>::itrator it;
    while(++r < len){
        # find the duplicate before a[r]
        it = find(a.begin(), a.begin()+r, a[r]);
        # remove the duplicate if it is found
        if(it!=a.begin()+r) a.erase(it);
    }
}

 

 

 

      1.2.有序線性表

     以重復區間為單位批量刪除. 對於向量[2,2,2,3,3,3,6,6,6,6,9,9],設兩個指針i, j, 初始時 i 指向第一個元素, j 指向緊鄰i 的第二個元素, 如果a[i]=a[j], 則直接跳過(++j), 否則令i指向j所對應的元素, 然后++j 

vector<int> deduplicate(vector<int> a){
    int i=0, j = 0;
    int len = a.size();
# scan the vector the the end
while(++j < len){ # skip the duplicates if(a[i]!=a[j]) a[++i] = a[j]; } vector<int> newv(a.begin(), a.begin()+i+1); return newv; }

       

    

參考資料: 數據結構 c++第三版 鄧俊輝著


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM