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
posted @ 2018-10-18 13:42  narjaja  阅读(138)  评论(0编辑  收藏  举报