Find a number where it appears exactly N/2 times

后端 未结 20 1837
旧巷少年郎
旧巷少年郎 2021-01-29 23:17

Here is one of my interview question. Given an array of N elements and where an element appears exactly N/2 times and the rest N/2 elements are unique

20条回答
  •  醉梦人生
    2021-01-29 23:46

    Here is Don Johe's answer in Ruby:

    #!/usr/bin/ruby1.8
    
    def find_repeated_number(a)
      return nil unless a.size >= 3
      (0..a.size - 3).each do |i|
        [
          [0, 1],
          [0, 2],
          [1, 2],
        ].each do |j1, j2|
          return a[i + j1] if a[i + j1] == a[i + j2]
        end
      end
    end
    
    p find_repeated_number([1, 1, 2])   # => 1
    p find_repeated_number([2, 3, 2])   # => 1
    p find_repeated_number([4, 3, 3])   # => 1
    

    O(n)

提交回复
热议问题