169. Majority Element*

来源:互联网 发布:网络凶杀2 编辑:程序博客网 时间:2024/05/18 01:11

Given an array of size n, find the majority element. The majority element is the element that appearsmore than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


My code:

from collections import Counterclass Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        dict = Counter(nums)        n= len(nums)        for key in dict.keys():            if dict[key]> n/2:                return key

It seems that there is only one majority element in this problem 

method1

class Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        a= sorted(nums)        return a[len(nums)/2]
method2

Don't understand this method.

public class Solution {    public int majorityElement(int[] num) {        int major=num[0], count = 1;        for(int i=1; i<num.length;i++){            if(count==0){                count++;                major=num[i];            }else if(major==num[i]){                count++;            }else count--;                    }        return major;    }}




0 0