Find numbers in array that appear 2 or more times

46 views Asked by At

I need to find duplicated numbers (that appear 2 or more times) in array how can I do it without using NSCountedSet?

This is a solution I did:

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);
}];
1

There are 1 answers

0
Oleksandr Matrosov On

This is a solution that can be achieved using Swift, but you can use any language to achieve this result:

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")
      }
    }
  }