Lintcode46 Majority Number solution 題解

【題目描述】

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Notice:You may assume that the array is non-empty and the majority number always exist in the array.

給定一個整型數組,找出主元素,它在數組中的出現次數嚴格大於數組元素個數的二分之一。

注意:你可以假設數組中沒有非空和主元素。


【題目鏈接】

http://www.lintcode.com/en/problem/majority-number/


【題目解析】

最直觀的想法就是,建立HashMap,記錄list中的每一個integer元素的個數,如果大於1/2 list長度,即可返回。

進一步分析發現,其實並不需要記錄所有的integer元素的個數,可以只記錄當前最多的那一個majority。這種方法也稱爲: Boyer–Moore majority vote algorithm

換一種角度,是否可以直接從list中讀取這個majority呢?如果對list進行排序,那麼1/2處的元素,也就是majority的那個integer了。當然這種方法有個問題,就是對於沒有majority的情況下(沒有一個達到了1/2 總長度),是無法判斷是否存在majority的,如果題目中明確一定存在這樣的majority,那麼這種方法也是可行的。

時間 O(n), 空間 O(1)


【參考答案】

http://www.jiuzhang.com/solutions/majority-number/




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章