你不能使用正常的哈希表。我使用動態編程和散列表。
你必須讓你的哈希表是這樣的:
[數組的值,重複數,相同的對數]
例如,我們可以在陣列A = [3, 3, 3, 3, 3]
上運行我的算法。
我們走過Array。用於在第一數目,所述新的行被插入到哈希表
3,0,0 /* A[i], the number of repetition of 3 so far (Rep[i]),
the number of identical pair so far (Iden[i]). */
然後第二3中所述的:
3,1,1
第三3中所述的:
3,2,3
爲第四3中A:
3,3,6
6是id的個數在這個數組中的真正對。一般情況下,我們可以通過以下公式計算相同對數:
鑑定者[I] =代表[I] +鑑定者[I-1]
下面是在C#代碼示例:
public static int solution(int[] A)
{
int identical = 0;
Dictionary<int, KeyValuePair<int, int>> dic = new Dictionary<int, KeyValuePair<int, int>>(); /* A[i], the number of repetition of 3 so far (Rep[i]),
the number of identical pair so far (Iden[i]). */
for (int i = 0; i < A.Length; i++)
{
if (!dic.ContainsKey(A[i]))
dic.Add(A[i], new KeyValuePair<int, int>(0,0));
else
{
KeyValuePair<int,int> valDic = dic[A[i]];
KeyValuePair<int, int> newVal;
if (valDic.Key < 1)
newVal = new KeyValuePair<int, int>(1, 1);
else
{
int preIdenticalPair = valDic.Value;
int preReptation = valDic.Key;
int newRepetation = ++preReptation;
int newIdenticalPair = preIdenticalPair + newRepetation;
newVal = new KeyValuePair<int, int>(newRepetation, newIdenticalPair);
}
dic[A[i]] = newVal;
}
}
//summation of all identical pairs
foreach (KeyValuePair<int, KeyValuePair<int, int>> pair in dic)
identical += pair.Value.Value;
return identical;
}
如果您可以對數組進行排序,則總時間爲O(n log n) - 排序爲n log n,並且查找相同的元素將是線性的。 – 2014-11-06 05:33:28
是否允許負值?數組中int的最大/最小值是多少? – Marichyasana 2016-12-17 21:55:26