Finding a number that repeats even no of times where all the other numbers repeat odd no of times

前端 未结 5 450
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 01:41

Given is an array of integers. Each number in the array repeats an ODD number of times, but only 1 number is repeated for an EVEN number of times. Find that number.

相关标签:
5条回答
  • 2020-12-18 02:07

    I don't know what the intended meaning of "repeat" is, but if there is an even number of occurrences of (all-1) numbers, and an odd number of occurances for only one number, then XOR should do the trick.

    0 讨论(0)
  • 2020-12-18 02:08

    Hash-map is fine, but all you need to store is each element's count modulo 2. All of those will end up being 1 (odd) except for the 0 (even) -count element.

    (As Aleks G says you don't need to use arithmetic (count++ %2), only xor (count ^= 0x1); although any compiler will optimize that anyway.)

    0 讨论(0)
  • 2020-12-18 02:13

    You don't need to keep the number of times each element is found - just whether it's even or odd number of time - so you should be ok with 1 bit for each element. Start with 0 for each element, then flip the corresponding bit when you encounter the element. Next time you encounter it, flip the bit again. At the end, just check which bit is 1.

    0 讨论(0)
  • 2020-12-18 02:16

    Apparently there is a solution in O(n) time and O(1) space, since it was asked at a software engineer company with this constraint explictly. See here : Bing interview question -- it seems to be doable using XOR over numbers in the array. Good luck ! :)

    0 讨论(0)
  • 2020-12-18 02:26

    If all numbers are repeated even times and one number repeats odd times, if you XOR all of the numbers, the odd count repeated number can be found.

    By your current statement I think hashmap is good idea, but I'll think about it to find a better way. (I say this for positive integers.)

    0 讨论(0)
提交回复
热议问题