zoukankan      html  css  js  c++  java
  • 47.Majority Element I & II

    Majority Element I

    描述

    给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
    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

    挑战

    要求时间复杂度为O(n),空间复杂度为O(1)

    class Solution:
        """
        @param: nums: a list of integers
        @return: find a  majority number
        """
        def majorityNumber(self, nums):
            # write your code here
            tmp = nums[0]
            count = 1
            for num in nums[1:]:
                
                if count == 0 :
                    tmp = num
                    count = 1
                
                if tmp == num :
                    count+=1
                else:
                    count-=1
            
            return tmp
    

    Majority Element II

    描述

    给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。
    数组中只有唯一的主元素

    样例

    给出数组[1,2,1,2,1,3,3] 返回 1

    挑战

    要求时间复杂度为O(n),空间复杂度为O(1)。

    class Solution:
        """
        @param: nums: a list of integers
        @return: The majority number that occurs more than 1/3
        """
        def majorityNumber(self, nums):
            # write your code here
            if not nums:
                return []
            count1, count2, candidate1, candidate2 = 0, 0, 0, 0 
            for n in nums:
                if n == candidate1:                     
                   count1 += 1                       
                elif n == candidate2:
                   count2 += 1
                elif count1 == 0:                   
                   candidate1, count1 = n, 1
                elif count2 == 0:
                   candidate2, count2 = n, 1
                else:
                   count1, count2 = count1 - 1, count2 - 1
    
                #return [n for n in (candidate1, candidate2) if nums.count(n) > len(nums) // 3]
                if nums.count(candidate1) > len(nums) // 3 :
                    return candidate1
                elif nums.count(candidate2) > len(nums) // 3 :
                    return candidate2
    
  • 相关阅读:
    SDOI 2016 数字配对
    SDOI 2016 征途 决策单调性
    SDOI 2016 生成魔咒
    SDOI 2016 排列计数
    【SC主题公园杯】三个袋子 = =不动脑的后果
    【BZOJ3050】【USACO 2013 Jan Gold金组】坐座位 Seating
    MillerRabin 快速的素数概率判定法
    [POJ3189][cqbzoj1640]稳定的奶牛分配 解题报告
    最大流 isap 模板
    【POJ 1324】Holedox Moving A*宽搜
  • 原文地址:https://www.cnblogs.com/narjaja/p/9810009.html
Copyright © 2011-2022 走看看