Finding an element in an array that isn't repeated a multiple of three times?

前端 未结 3 1835
南笙
南笙 2020-12-14 03:04

After reading this interesting question I was reminded of a tricky interview question I had once that I never satisfactorily answered:

You are given a

3条回答
  •  醉话见心
    2020-12-14 04:08

    The obvious solution to do it in constant space is to sort it using an in place algorithm, and then scan once over the array.

    Sadly this requires usually O(n log n) time and O(1) space.

    But as the entries have a limited key length (32 bit) you can use as sort algorithm radix sort (there exist in place radix sort, they are not stable, but that doesnt matter here). There you have O(n) time and O(1) space.

    EDIT: Btw you could use this approach to find also ALL numbers that appear not a multiple of 3 times, in case you would allow that more than one number could have this property.

提交回复
热议问题