【发布时间】:2019-08-01 12:50:33
【问题描述】:
我正在使用 HashSet 来查找 排序 Integer 数组中值的最大重复数。但是我的算法似乎不起作用,没有返回想要的结果。
Set variables storing the number of duplicates found (0), and the maximum number of duplicates (0).
Set a HashSet that stores the unique values of an array.
Sort the array to be ready for comparison.
Loop through each value of the array
If the HashSet of unique values contains the current value:
Increment the duplicate Count
If the currentValue is not equal to the previous value:
If the duplicateCount is greater than the maximum Count:
maximumCount becomes duplicateCount
Reset duplicateCount to 0
Java 代码:
HashSet<Integer> uniqueValues = new HashSet<Integer>(valueSequenceList);
int duplicateCount = 0;
int maxCount = 0;
Arrays.sort(valueSequence);
for (int i = 0; i < valueSequence.length; i++)
{
if (uniqueValues.contains(valueSequence[i]))
{
duplicateCount++;
}
if (i > 0 && valueSequence[i] != valueSequence[i-1])
{
if (duplicateCount > maxCount)
{
maxCount = duplicateCount;
duplicateCount = 0;
}
}
}
示例:
输入:[4, 4, 10, 4, 10]
输出:4 个重复项(最多应该有 3 个重复项 - 相同的值的总数)。
【问题讨论】:
-
您的示例未排序,而问题说应该排序。
-
@amit 我在我的代码中对数组进行了排序。我忘了把它添加到问题中。
-
@HenryIsVeryPro 然后更新问题而不是发表评论!
-
@HenryIsVeryPro,您不需要 HashSet,只需检查
valueSequence[i] == valueSequence[i-1]。 -
@aioobe 哦,是的,好点。让我检查一下。