Find a special number in an array

后端 未结 9 1668
天命终不由人
天命终不由人 2020-12-25 09:07

There are many numbers in an array and each number appears three times excepting for one special number appearing once. Here is the question: how can I find the special numb

9条回答
  •  梦谈多话
    2020-12-25 10:00

    A possible algorithm (very generic, not tested) :

    function findMagicNumber(arr[0...n])
       magic_n := NaN
    
       if n = 1 then
          magic_n := arr[0]
       else if n > 1 then
          quicksort(arr)
    
          old_n := arr[0]
          repeat := 0
    
          for i := 1 to n
             cur_n := arr[i]
             repeat := repeat + 1
             if cur_n ≠ old_n then
                if repeat = 1 then
                   magic_n := old_n
                old_n := cur_n
                repeat := 0
    
       return magic_n
    

提交回复
热议问题