LintCode 46. Majority Number

原题

LintCode 46. Majority Number

Description

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Notice

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

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

解题

思路一

最简单的思路就是用Map统计每个数字出现的次数,然后取出现次数最多的数,即为答案。

class Solution {
public:
    /**
    * @param nums: A list of integers
    * @return: The majority number
    */
    int majorityNumber(vector<int> nums) {
        // write your code here
        map<int, int> m;
        auto vit = nums.begin();
        while (vit != nums.end()) {
            if (m.find(*vit) == m.end()) m[*vit] = 0;
            m[*vit]++;
            vit++;
        }
        auto mit = m.begin();
        int maxNum = 0;
        int maxCount = 0;
        while (mit != m.end()) {
            if (mit->second > maxCount) {
                maxCount = mit->second;
                maxNum = mit->first;
            }
            mit++;
        }
        return maxNum;
    }
};

思路二

如果要求空间复复杂度O(1),可以用如下思路:
将每个数字理解为一个议案,那么每出现一次其实就是为这个议案的票数+1,如果出现其他议案,那么票数-1。当票数为0的时候,切换到下一个议案。
如果Majority Number一定存在,那么它的票数就一定不会被减到0,最后胜出。

class Solution {
public:
    /**
    * @param nums: A list of integers
    * @return: The majority number
    */
    int majorityNumber(vector<int> nums) {
        // write your code here
        int candidate, count = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (count == 0) {
                candidate = nums[i];
                count++;
            } else {
                if (candidate == nums[i])
                    count++;
                else
                    count--;
            }
        }
        return candidate;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,131评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,792评论 0 33
  • 这是我的小猪佩奇,它是我在宝鸡买的,他很可爱,而且它还有一个特点,就是它的双腿和双手都可以动,其实它的脖子也可...
    5505王妙伊阅读 396评论 0 1
  • 是心都会痛,是人都难懂, 不是每次微笑都代表着开心, 也不是每次流泪,都很伤痛, 谁都有说不出的苦衷, 只是没有人...
    殇感记语阅读 194评论 0 1