169. Majority Element*

49人阅读 评论(0)

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.

My code:

from collections import Counter
class 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 ｍａjority 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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：45771次
• 积分：3739
• 等级：
• 排名：第8620名
• 原创：331篇
• 转载：87篇
• 译文：0篇
• 评论：9条
评论排行
最新评论