lintcode--主元素

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


 注意事項

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

樣例

給出數組[1,1,1,1,2,2,2],返回 1






public class Solution {
    /**
     * 第二種方法 時間複雜度爲O(n),空間複雜度爲O(1)  
        //因爲主元素個數至少大於等於數組元素的一般  
        //所以先nums[0]賦值給temp,再遍歷數組,若等於temp,則n++,否則n--,
            當n=0時交換temp的值並把n置1。  
        //最後的temp就是主元素。  
     */
    public int majorityNumber(ArrayList<Integer> nums){
        int n = 1;//計數
        int temp = nums.get(0);//先賦值給date,
        for(int i =1;i<nums.size();i++){//再遍歷數組
           
           if(temp == nums.get(i)){//若等於temp,則n++,
                n++;
            }else{
                n--;//不相同否則--
            }
            if(n == 0){//當n=0時交換temp的值並把n置1。  
                temp = nums.get(i);//
                n =1;
            }
        }
        return temp;//當n不爲0的時候的數
    }
}

發佈了124 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章