Majority Element

題目
Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.
You may assume that the array is non-empty and the majority element always exist in the array.

答案

class Solution {
    public int majorityElement(int[] nums) {
        int candidate_idx = 0, count = 1;
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] == nums[candidate_idx])
                count++;
            else
                count--;
            if(count == 0) {
                candidate_idx = i;
                count = 1;
            }
        }
        return nums[candidate_idx];
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,424評論 0 10
  • 細雨伴春游,花枝濺我衣。 山高云杳杳,偶有喚娘聲。 明宮多喧鬧,當年殿上爭。 君王身后事,已是少人聞。
    玉折蘭摧閱讀 1,639評論 0 49
  • 繼續記錄!堅持不懈!堅持是我的硬傷,這次一定要療傷到痊愈!!!因為我有我的小蝸牛一起!! 回來做記錄第二天,因為很...
    燁媽閱讀 262評論 0 0
  • 調暗的屏幕里面沒有你 可是你發的每一個字都像星星 一閃一閃就像我跳動的心 沒遇到你之前 我只想脫貧 遇到你之后 突...
    驀然_7b5d閱讀 203評論 0 0
  • 曾國藩是春秋戰國時代曾子的七十世孫。他是中國近代政治家、戰略家、理學家、文學家,湘軍的創立者和統帥;他因為在學問和...
    般若秋雪閱讀 254評論 0 2