Finding first non-repeating number in integer array

后端 未结 4 1708
天涯浪人
天涯浪人 2021-02-20 03:55

I got this question for an exam:

Given an integer array find the first number which is not repeating in array using O(N) time complexity and O(1) space co

4条回答
  •  时光说笑
    2021-02-20 04:21

    I believe the trick to solve the problem is :

    max size of array would be 1million

    since :

    O(1) space means that the memory required by the algorithm is constant

    then space complexity will automatically becomes O(1) given the constant 1M. NOTE. 1M is still a constant number even though its a really large number. thus we only need to concentrate on time complexity.

    Using a LinkedHashMap we can add a new element with O(1) and retrieve element with O(1) thus updating an entry will take O(1) too. it also preserves the order. therefore, we can find the earliest entry

    then the problem will become simple in two steps:

    1. build up the LinkedHashMap --> O(n)
    2. find the earliest number which its count is 0 --> O(n)

    each of the above steps requires O(n) thus overall time complexity is O(2n) = O(n).

提交回复
热议问题