leetcode 169. Majority Element

原创 2016年05月31日 19:39:01

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.



好吧,我承认我懒。。看完题只能想到暴力,还懒得去实现……看了别人的算法后才写的,就知道这道题肯定有好的办法。。算法叫Moore’s Voting Algorithm。O(n)的复杂度,很奇妙的想法。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int m,num=0;
        for(int i=0;i<nums.size();i++)
        {
            if(num==0) 
            {
                m=nums[i];
                num=1;
            }
            else
            {
                if(m==nums[i])
                    num++;
                else num--;
                if(num>nums.size()/2) return m;
            }
        }
        return m;
    }
};

相关文章推荐

【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...

【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...

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

【leetcode】169. Majority Element

一、题目描述 Given an array of size n, find the majority element. The majority element is the element...

Leetcode 169. Majority Element[easy]

GRE回归,响应老师号召,做分治题目。题目: Given an array of size n, find the majority element. The majority element is...

第二周:[LeetCode]169. Majority Element

[LeetCode]169. Majority ElementGiven an array of size n, find the majority element. The majority ele...
  • line02
  • line02
  • 2017年03月03日 12:18
  • 91
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 169. Majority Element
举报原因:
原因补充:

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