zoukankan      html  css  js  c++  java
  • 169. 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.

    Example 1:

    Input: [3,2,3]
    Output: 3

    Example 2:

    Input: [2,2,1,1,1,2,2]
    Output: 2

    找一个数,出现次数大于数字长度的一半。on做法维护一个majority数和他当前遇到相同数的个数,如果下一个数相同,计数+1,否则计数-1,计数=0的时候换majority,因为要找的数长度一定大于数组的一半,因此最后剩下来的数一定是majority
    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            majority = nums[0]
            count = 1
            for i in range(1, len(nums), 1):
                if nums[i] == majority:
                    count += 1
                else:
                    count -= 1
                if count == 0:
                    majority = nums[i]
                    count = 1
            return majority
            
            
  • 相关阅读:
    [ZJOI2011]营救皮卡丘
    TJOI2018Party
    HEOI2013SAO
    [BJOI2017]树的难题
    [HNOI2016]序列
    [SHOI2007]善意的投票
    CF802C Heidi and Library (hard)
    SPOJ DIVCNT2
    LOJ子序列
    BZOJ2882工艺
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13223202.html
Copyright © 2011-2022 走看看