Algorithm - How to delete duplicate elements in a list efficiently?

前端 未结 16 2160
执念已碎
执念已碎 2020-12-01 04:21

There is a list L. It contains elements of arbitrary type each. How to delete all duplicate elements in such list efficiently? ORDE

16条回答
  •  日久生厌
    2020-12-01 04:29

    I've written an algorithm for string. Actually it does not matter what type do you have.

    static string removeDuplicates(string str)
    {
        if (String.IsNullOrEmpty(str) || str.Length < 2) {
            return str;
        }
    
        char[] arr = str.ToCharArray();
        int len = arr.Length;
        int pos = 1;
    
        for (int i = 1; i < len; ++i) {
    
            int j;
    
            for (j = 0; j < pos; ++j) {
                if (arr[i] == arr[j]) {
                    break;
                }
            }
    
            if (j == pos) {
                arr[pos] = arr[i];
                ++pos;
            }
        }
    
        string finalStr = String.Empty;
        foreach (char c in arr.Take(pos)) {
            finalStr += c.ToString();
        }
    
        return finalStr;
    }
    

提交回复
热议问题