Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2150
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

24条回答
  •  一向
    一向 (楼主)
    2020-11-28 07:17

    Sorting the array would seem to be the best solution. A simple sort would then make the search trivial and would take a whole lot less time/space.

    Otherwise, if you know the domain of the numbers, create an array with that many buckets in it and increment each as you go through the array. something like this:

    int count [10];
    
    for (int i = 0; i < arraylen; i++) {
        count[array[i]]++;
    }
    

    Then just search your array for any numbers greater than 1. Those are the items with duplicates. Only requires one pass across the original array and one pass across the count array.

提交回复
热议问题