Find first unique number from array

时间:2016-11-12 21:59:32

标签: c# arrays algorithm

I am trying to answer a test using C# and the question is to find the first unique number from a given array A of N integers. If there is no unique number in the array then return -1.

For example, if A = {4,5,4,6,5,5,3,8,6} then return 3
if A = {3,2,3,2,3} then return -1

Range of each element of array A is [0..1,000,000,000], and range of N is [1..100,000],

Expected worst-case time complexity - O(N*Log(N))
Expected worst-case space complexity - O(N), beyond input storage

I am able to write the below solution that uses a List variable to store the duplicate numbers when iterating through the array A.
My questions are as follows:
1. Is this solution meets the complexity requirement as mentioned above?
2. Is there a better approach/algorithm of doing this in C#, without using LINQ?

 public int solution(int[] A)
    {

        if (A.Length == 1)
        {
            return A[0];
        }
        else if (A.Length == 2)
        {
            if (A[0] == A[1])
            {
                return -1;
            }
            else
            {
                return A[0];
              }
        }
        else
        {
            List<int> duplicateList = new List<int>();

            bool isDuplicate = false;
            for (int index = 0; index < A.Length - 1; index++)
            {                    
                if (duplicateList.IndexOf(A[index]) == -1)
                {
                    isDuplicate = false;
                    duplicateList.Add(A[index]);

                    for (int searchIndex = index + 1; searchIndex < A.Length; searchIndex++)
                    {
                        if (A[index] == A[searchIndex])
                        {
                            isDuplicate = true;
                        }
                        if (isDuplicate)
                        {
                            break;
                        }

                        if (searchIndex == A.Length - 1 && isDuplicate == false)
                        {
                            return A[index];
                        }
                    }

                }
            }

            if ((duplicateList.IndexOf(A[A.Length - 1])) == -1)
            {
                return A[A.Length - 1];
            }
            else return -1;
        }
    }

1 个答案:

答案 0 :(得分:2)

您的答案的时间复杂度为O(n^2),可以从嵌套循环结构中轻松推断出来,甚至更多,具体取决于List中indexOf调用的实现。

因此要将其优化为O(nlogn),您可以使用C#中的Dictionary接口将数字及其出现频率及其索引存储在数组中作为Key,Value对,然后遍历Dictionary以查找第一个数组中的数字,频率为1.

相关问题