169. Majority Element*

原创 2016年08月28日 16:28:24

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 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;
    }
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)

Question1Given an array of size n, find the majority element. The majority element is the element th...

[leetcode] 169.Majority Element

题目: Given an array of size n, find the majority element. The majority element is the element that a...

leetcode[169]:Majority Element

Majority Element Given an array of size n, find the majority element. The majority element is the e...

[169] Majority Element

给定一个数组,找到数组中的主要元素,即这个元素占数组的总元素个数的1/2以上。...
  • camlot_
  • camlot_
  • 2016年07月20日 21:35
  • 110

【LEETCODE】169-Majority Element

Given an array of size n, find the majority element. The majority element is the element that appear...

LeetCode 169. Majority Element(众数)

原题网址:https://leetcode.com/problems/majority-element/ Given an array of size n, find the majority e...
  • jmspan
  • jmspan
  • 2016年05月25日 01:37
  • 466

【leetcode】Array—— Majority Element(169)

题目: 思路1:sort  很简单,把nums排序后,直接取下彪为num.length/2的值 代码:public int majorityElement1(int[] nums) { Arr...

LeedCode169. Majority Element

169. Majority Element Given an array of size n, find the majority element. The majori...

Leetcode 169 - Majority Element(Moore投票算法)

题意给一个数组,求它的majority,对majority的定义为:出现次数超过⌊n2⌋\lfloor \frac{n}{2} \rfloor的元素。思路算法1O(nlogn)O(nlogn)时间。排...
  • Lzedo
  • Lzedo
  • 2017年02月15日 22:03
  • 115

169. Majority Element

leetcode169 - Easy - Discuss
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:169. Majority Element*
举报原因:
原因补充:

(最多只允许输入30个字)