Array Homework Question

前端 未结 9 1262
庸人自扰
庸人自扰 2020-12-23 16:48

You are given an array with integers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using littl

9条回答
  •  天涯浪人
    2020-12-23 17:04

    As a variant of your solution (2), you can use radix sort. No extra memory, and will run in linear time. You can argue that time is also affected by the size of numbers representation, but you have already given bounds for that: radix sort runs in time O(k n), where k is the number of digits you can sort ar each pass. That makes the whole algorithm O(7n)for sorting plus O(n) for checking the duplicated number -- which is O(8n)=O(n).

    Pros:

    • No extra memory
    • O(n)

    Cons:

    • Need eight O(n) passes.

提交回复
热议问题