Find a single integer that occurs with even frequency in a given array of ints when all others occur odd with frequency

后端 未结 5 1408
盖世英雄少女心
盖世英雄少女心 2021-02-03 10:26

This is an interview question.

Given an array of integers, find the single integer value in the array which occurs with even frequency. All integers will be

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-03 11:02

    -Make a hash table containing ints. Call it is_odd or something. Since you might have to look through an array of size INT_MAX, just make it an array of size INT_MAX. Initialize to 0.

    -Traverse through the whole array. You have to do this. There's no way to beat O(n).

    for each number:
      if it's not in the hash table, mark its spot in the table as 1.
    
      if it is in the hash table then:
        if its value is '1', make it '2'
        if its value is '2', make it '1'.
    

    Now you have to traverse through the hash table. Pull out the sole entry with "2" as the value.

    Time: You traverse the array once and the hash table once, so O(n).

    Space: Just an array of size INT_MAX. Or if you know the range of your array you can restrict your memory use to that.

    edit: I just saw that you already had this method. Sorry about that!

提交回复
热议问题