你不能使用普通的哈希表。我使用了动态编程和哈希表。
你应该像这样设置你的哈希表:
[数组的值,重复次数,相同对的数量]
例如,我们可以在数组A = [3, 3, 3, 3, 3] 上运行我的算法。
我们遍历数组。对于 A 中的第一个数字,将新行插入到哈希表中
3,0,0 /* A[i], the number of repetition of 3 so far (Rep[i]),
the number of identical pair so far ( Iden[i]). */
然后在 A 中的第二个 3:
3,1,1
A 中的第三个 3:
3,2,3
A 区第 4 3 位:
3,3,6
6 是该数组中相同对的数量。一般来说,我们可以通过以下公式计算相同对的数量:
Iden[i] = Rep[i] + Iden[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;
}