Limit input data to achieve a better Big O complexity

前端 未结 3 1966
傲寒
傲寒 2020-12-22 14:40

You are given an unsorted array of n integers, and you would like to find if there are any duplicates in the array (i.e. any integer appearing more than once). D

3条回答
  •  不知归路
    2020-12-22 15:08

    You can do linearly (O(n)) for any input if you use hash tables (which have constant look-up time).

    However, this is not what you are being asked about.

    By limiting the possible values in the array, you can achieve linear performance.

    E.g., if your integers have range 1..L, you can allocate a bit array of length L, initialize it to 0, and iterate over your input array, checking and flipping the appropriate bit for each input.

提交回复
热议问题