Easy-题目11:169. Majority Element

转载 2016年05月30日 19:54:23

题目原文:
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.
题目大意:
找出一个数组的主元素,即在数组中出现的次数>n/2.
分析:
使用repeatTimes变量记录主元素重复次数,每次遇到重复的就+1,不重复的就-1.减到0时就更新当前主元素。(利用主元素出现次数比其他数出现之和多这一性质。)
源码:(language:c)

int majorityElement(int* nums, int numsSize) {
    int i,mainElement,repeatTimes = 0;  

    //每次若不相同则减小这个计数,若相同则增加  
    for(i = 0;i<numsSize;i++) {  
        if(repeatTimes == 0){  
            mainElement = nums[i];  
            repeatTimes = 1;  
        }  
        else{  
            if(mainElement == nums[i])  
                repeatTimes++;  
            else  
                repeatTimes--;  
        }  
    }  
    return mainElement;  
}

成绩:
8ms,beats 36.16%.众数:8ms 63.84%
Cmershen的碎碎念:
此题好像是考研408模拟题中的一道题,听说也经常在面试中出现。一开始我想到的是用HashMap记录每个元素出现的次数,最大的就是主元素。但这样的空间复杂度就是O(n),而上述算法有更优的O(1)空间复杂度。

相关文章推荐

Leetcode 169. Majority Element[easy]

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

169. Majority Element [easy] (Python)

题目链接https://leetcode.com/problems/majority-element/题目原文 Given an array of size n, find the majorit...

【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以上。

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

【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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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