Guest User

Untitled

a guest
Nov 22nd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. package missingnumbers
  2.  
  3. // My solution
  4. //
  5. // Store each value as a bit in an array
  6. // of 64 bit "words". Then find all words which
  7. // hasn't all bits set. And in that word find the missing bits.
  8. // So bit 66 is stored in word 1 bit 2
  9.  
  10. // How big is a word (64 since I use uint64)
  11. const wordSize = 64
  12. // a 64-bit number with all bits set
  13. const wordAllSet = 0xffffffffffffffff
  14. // Mask to use instead of modulo wordSize
  15. const moduloMask = 63
  16.  
  17. type bitArray struct {
  18. len int // Total number of bits
  19. nWords int // THe number of words used
  20. words []uint64
  21. }
  22.  
  23. func newBitArray(len int) bitArray {
  24. nWords := len / wordSize
  25. if len & moduloMask != 0 {
  26. nWords++
  27. }
  28. words := make([]uint64, nWords, nWords)
  29. return bitArray{len: len, nWords: nWords, words: words}
  30. }
  31.  
  32. func (b *bitArray) setBit(n int) {
  33. index := n / wordSize
  34. bit := uint64(1) << uint(n & moduloMask)
  35. b.words[index] |= bit
  36. }
  37.  
  38. func (b *bitArray) findUnsetBits(maxCount int) []int {
  39. unset := make([]int, 0, maxCount)
  40. for i, word := range b.words {
  41. if word & wordAllSet != wordAllSet {
  42. j := 0
  43. for j < wordSize {
  44. if word & (uint64(1) << uint(j)) == 0 {
  45. unset = append(unset, i * wordSize + j)
  46. if len(unset) == maxCount {
  47. return unset
  48. }
  49. }
  50. j++
  51. }
  52. }
  53. }
  54. return unset
  55. }
  56.  
  57. func Missing(numbers []int) []int {
  58. bits := newBitArray(len(numbers) + 3) // 0 and 2 missing numbers
  59. bits.setBit(0)
  60. for _, number := range numbers {
  61. bits.setBit(number)
  62. }
  63. return bits.findUnsetBits(2)
  64. }
Add Comment
Please, Sign In to add comment