私はC#を使ってテストに答えようとしていますが、問題は配列のN個の整数から最初のユニークな番号を見つけることです。配列に一意の番号がない場合は-1を返します。配列から最初のユニークな番号を見つける
たとえば、A = {4,5,4,6,5,5,3,8,6}の場合、A = {3,2,3,2,3}ならば3
を返します。 O(N *ログ( - -1
予想最悪の場合の時間計算、配列Aの各要素の
範囲[0..1,000,000,000]であり、そしてNの範囲は[1..100,000]でありますN))
予想される最悪の場合の空間の複雑さ - 入力記憶域を超えたO(N)
配列変数Aを反復処理するときにList変数を使用して重複する数値を格納する以下のソリューションを記述できます。
1.このソリューションは、上記の複雑さ要件を満たしていますか?
2. LINQを使用せずにC#でこれを行うより良いアプローチ/アルゴリズムがありますか?
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;
}
}
私はあなたのアプローチを実装し、それをテストしました。 1M個の数値を含む配列の最悪の場合のシナリオでは、以前のソリューションの実行時間は71ミリ秒でしたが、ソリューションの場合はわずか48ミリ秒でした。あなたの助けと時間をありがとう。 –