我需要在数组中找到重复的数字(出现2次或更多次),如何在不使用NSCountedSet
的情况下执行此操作?
这是我做的一个解决方案:
NSCountedSet *countedSet = [NSCountedSet setWithArray:array];
__block NSUInteger totalNumberOfDuplicates = 0;
[countedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop)
{
NSUInteger duplicateCountForObject = [countedSet countForObject:obj];
if (duplicateCountForObject > 1)
totalNumberOfDuplicates += duplicateCountForObject;
NSLog(@"%@ appears %ld times", obj, duplicateCountForObject);
}];
答案 0 :(得分:1)
这是一个可以使用Swift实现的解决方案,但您可以使用任何语言来实现此结果:
func checkDuplicatedNumbers()
{
let array = [1, 2, 3, 4, 0, 1, 5, 2, 1, 1, 1, 4]
var dictioanry = [Int: Int]()
for element in array
{
if let value = dictioanry[element] {
let newValue = value + 1
dictioanry[element] = newValue
} else {
dictioanry[element] = 1
}
}
for key in dictioanry.keys {
let count = dictioanry[key]
if (count > 1) {
print("Number \(key) repeats \(count) times")
}
}
}