How do I remove duplicates from a C# array?

后端 未结 27 2749
北海茫月
北海茫月 2020-11-22 07:53

I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was w

27条回答
  •  爱一瞬间的悲伤
    2020-11-22 08:35

    Here is a O(n*n) approach that uses O(1) space.

    void removeDuplicates(char* strIn)
    {
        int numDups = 0, prevIndex = 0;
        if(NULL != strIn && *strIn != '\0')
        {
            int len = strlen(strIn);
            for(int i = 0; i < len; i++)
            {
                bool foundDup = false;
                for(int j = 0; j < i; j++)
                {
                    if(strIn[j] == strIn[i])
                    {
                        foundDup = true;
                        numDups++;
                        break;
                    }
                }
    
                if(foundDup == false)
                {
                    strIn[prevIndex] = strIn[i];
                    prevIndex++;
                }
            }
    
            strIn[len-numDups] = '\0';
        }
    }
    

    The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.

提交回复
热议问题