TreeviewCopyright © aleen42 all right reserved, powered by aleen42

169. 多数元素

https://leetcode-cn.com/problems/majority-element/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-10-27 14:30:14
 * @LastEditTime: 2020-10-27 14:30:53
 * @Description: https://leetcode-cn.com/problems/majority-element/
 * @FilePath: \leetcode-googtech\#169. Majority Element\Solution.java
 * @WebSite: https://algorithm.show/
 */
class Solution {
    // 摩尔投票法
    public int majorityElement(int[] nums) {
        int count = 0, result = 0;
        for(int i = 0; i < nums.length; i++) {
            if(count == 0) {
                result = nums[i];
                count++;
            }else {
                if(result == nums[i]) count++;
                else count--;
            }
        }
        return result;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-10-27 14:30:25
LastEditTime: 2020-10-27 14:31:13
Description: https://leetcode-cn.com/problems/majority-element/
FilePath: \leetcode-googtech\#169. Majority Element\Solution.py
WebSite: https://algorithm.show/
'''
class Solution(object):
    # 摩尔投票法
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result, count = 0, 0
        for num in nums:
            if count == 0:
                result = num
            if num != result:
                count -= 1
            else:
                count += 1
        return result
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""