Loading [MathJax]/jax/input/TeX/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Leetcode 169 Majority Element

Leetcode 169 Majority Element

作者头像
triplebee
发布于 2018-01-12 06:48:28
发布于 2018-01-12 06:48:28
41100
代码可运行
举报
运行总次数: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.

Credits: Special thanks to @ts for adding this problem and creating all test cases.

找出出现次数超过一半的数字。

做法太多,花式过,我用的hash,贴上了讨论版中的几种常见做法,bitmap很有新意

Well, if you have got this problem accepted, you may have noticed that there are 7 suggested solutions for this problem. The following passage will implement 6 of them except the O(n^2) brute force algorithm.

Hash Table

The hash-table solution is very straightforward. We maintain a mapping from each element to its number of appearances. While constructing the mapping, we update the majority element based on the max number of appearances we have seen. Notice that we do not need to construct the full mapping when we see that an element has appeared more than n / 2 times.

The code is as follows, which should be self-explanatory.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> counts; 
        int n = nums.size();
        for (int i = 0; i < n; i++)
            if (++counts[nums[i]] > n / 2)
                return nums[i];
    }
};

Sorting

Since the majority element appears more than n / 2 times, the n / 2-th element in the sorted nums must be the majority element. This can be proved intuitively. Note that the majority element will take more than n / 2 positions in the sorted nums (cover more than half of nums). If the first of it appears in the 0-th position, it will also appear in the n / 2-th position to cover more than half of nums. It is similar if the last of it appears in the n - 1-th position. These two cases are that the contiguous chunk of the majority element is to the leftmost and the rightmost in nums. For other cases (imagine the chunk moves between the left and the right end), it must also appear in the n / 2-th position.

The code is as follows, being very short if we use the system nth_element (thanks for @qeatzy for pointing out such a nice function).

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
        return nums[nums.size() / 2];
    } 
};

Randomization

This is a really nice idea and works pretty well (16ms running time on the OJ, almost fastest among the C++ solutions). The proof is already given in the suggested solutions.

The code is as follows, randomly pick an element and see if it is the majority one.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        srand(unsigned(time(NULL)));
        while (true) {
            int idx = rand() % n;
            int candidate = nums[idx];
            int counts = 0; 
            for (int i = 0; i < n; i++)
                if (nums[i] == candidate)
                    counts++; 
            if (counts > n / 2) return candidate;
        }
    }
};

Divide and Conquer

This idea is very algorithmic. However, the implementation of it requires some careful thought about the base cases of the recursion. The base case is that when the array has only one element, then it is the majority one. This solution takes 24ms.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        return majority(nums, 0, nums.size() - 1);
    }
private:
    int majority(vector<int>& nums, int left, int right) {
        if (left == right) return nums[left];
        int mid = left + ((right - left) >> 1);
        int lm = majority(nums, left, mid);
        int rm = majority(nums, mid + 1, right);
        if (lm == rm) return lm;
        return count(nums.begin() + left, nums.begin() + right + 1, lm) > count(nums.begin() + left, nums.begin() + right + 1, rm) ? lm : rm;
    }
}; 

Moore Voting Algorithm

A brilliant and easy-to-implement algorithm! It also runs very fast, about 20ms.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int major, counts = 0, n = nums.size();
        for (int i = 0; i < n; i++) {
            if (!counts) {
                major = nums[i];
                counts = 1;
            }
            else counts += (nums[i] == major) ? 1 : -1;
        }
        return major;
    }
};

Bit Manipulation

Another nice idea! The key lies in how to count the number of 1's on a specific bit. Specifically, you need a mask with a 1 on the i-the bit and 0 otherwise to get the i-th bit of each element in nums. The code is as follows.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int major = 0, n = nums.size();
        for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) {
            int bitCounts = 0;
            for (int j = 0; j < n; j++) {
                if (nums[j] & mask) bitCounts++;
                if (bitCounts > n / 2) {
                    major |= mask;
                    break;
                }
            }
        } 
        return major;
    } 
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-01-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
leetcode-169-Majority Element
题目描述: 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. 要完成的函数: int majorityElement(
chenjx85
2018/05/21
5650
关小刷刷题02——Leetcode 169. Majority Element 方法2和3
题目 169. Majority Element 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. 方法2 方法2:把
WZEARW
2018/04/08
6220
leetcode 169 Majority Element 冰山查询
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
流川疯
2019/01/18
3770
LeetCode169. Majority Element解答
我及其喜欢这个算法,代码简洁高效,只用了一遍遍历。不过它的核心思想我还没有参透,用这个代码一步步调试过,但是没有时间细细思考为什么这个算法可以得到正确答案,以后有时间了再来挖坟
vincentbbli
2021/08/18
2130
LeetCode 169. Majority Element题目分析代码
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
desperate633
2018/08/22
3480
LeetCode 169. Majority Element题目分析代码
Leetcode 169. Majority Element
版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82693029
Tyan
2019/05/25
2550
【每日算法Day 90】5种方法:求解数组中出现次数超过一半的那个数
这个方法最简单,用哈希表记录每个数字出现的次数,最后看哪个数字次数超过一半就行了。
godweiyang
2020/04/14
7300
关关的刷题日记01—Leetcode 169. Majority Element
【导读】主题链路知识是我们专知的核心功能之一,为用户提供AI领域系统性的知识学习服务,一站式学习人工智能的知识,包含人工智能( 机器学习、自然语言处理、计算机视觉等)、大数据、编程语言、系统架构。使用请访问专知进行主题搜索查看 - 桌面电脑访问www.zhuanzhi.ai, 手机端访问www.zhuanzhi.ai 或关注微信公众号后台回复"专知"进入专知,搜索主题查看。Leetcode刷题是应届生找工作必备,我们专知平台专门邀请关关大美女写她的刷题日记,由入门到现在已经刷题200多道了,从今天开始
WZEARW
2018/04/08
8360
关关的刷题日记01—Leetcode 169. Majority Element
LeetCode笔记:169. Majority Element
第一直觉是先排序把相同的元素都放到一起再说,因为主要元素的出现次数大于n/2,那么排序后最中间的元素一定是主要元素,不管怎么移动位置,最中间的都一定是它,所以可以很简单地完成代码啦。
Cloudox
2021/11/23
1870
Q169 Majority Element
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. 解题思路: 将每个元素出现的次数用 Map 保存起来,返回出现次数最
echobingo
2018/04/25
8860
LeetCode 169. 求众数(摩尔投票)
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
Michael阿明
2021/02/20
6380
LeetCode 169. 求众数(摩尔投票)
Leetcode 229. Majority Element II
版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82693040
Tyan
2019/05/25
4320
算法:分治
分治是一种将大问题分解成相同任务的小问题的方法,常见的分治思想之一就是归并排序(mergeSort)
用户3578099
2022/04/18
1K0
算法:分治
LeetCode 169. Majority Element
思路:数组中有一个数字的出现次数超过一半,也就是说这个数字的出现次数比其他的所有的数字的出现次数之和还要多。因此我们可以考虑遍历数组的时候保存两个值,一个是数组中的数字,一个数次数。当我们遍历到下一个数字的时候,如果下一个数字与我们之前保存的数字是相同的,那么次数加1,不同则减1,。如果次数为0,那么我们需要保存下一个数字,并把次数设置为1,。由于我们要找到的数字比其他的所有的数字的出现次数还要高,那么我们要找的数字一定是最后一次把次数设置为1时候所对应的数字。
大学里的混子
2018/10/30
4550
LeetCode 0169 - Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
Reck Zhang
2021/08/11
1930
Leetcode#169. Majority Element(求众数)
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
武培轩
2018/09/28
1.3K0
单调队列问题-LeetCode 239、169(单调队列,Boyer-Moore投票法)
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。
算法工程师之路
2019/11/14
1.4K0
LeetCode 0229 - Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Reck Zhang
2021/08/11
1590
LeetCode169 Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
用户1665735
2019/02/19
3970
Leetcode: Majority Element
问题描述: 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.
卡尔曼和玻尔兹曼谁曼
2019/01/25
5120
相关推荐
leetcode-169-Majority Element
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验