主元素問題python和Java解法

Python版:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        
        temp = -1
        c = 0
        for l in nums:
            if temp == -1:
                temp = l
                c = 1
            else:
                if c == 0:
                    temp = l
                    c = 1
                elif temp == l:
                    c += 1
                else:
                    c -= 1
        return temp

Java版

class Solution {
    public int majorityElement(int[] nums) {
        int temp = -100;
        int c = 0;
        for(int i=0; i<nums.length; i++){
            if(temp == -100){
                temp = nums[i];
                c = 1;
            }else{
                if(c == 0){
                    temp = nums[i];
                    c = 1;
                }else if(temp == nums[i])
                    c += 1;
                else{
                    c -= 1;
                }
            }
        }
        return temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章