Majority Element
来源:互联网 发布:编写java游戏小程序 编辑:程序博客网 时间:2024/06/07 04:18
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.
Divide and Conquer Array Bit Manipulation
这道题的解法很多,官方推荐解法如下:
我这里主要实现【二种方法】:
1.sort方法:(nlogn)
思路:.
默认升序排序,取len/2即中点,值肯定为the majority element
<span style="white-space:pre"></span>//sort:时间复杂度O(nlogn)。最漂亮的解,不是最优解int majorityElement0(vector<int>& nums) {int len = nums.size();sort(nums.begin(), nums.end());return nums[len / 2];}2.Moore voting algorithm(摩尔投票算法): (o(n))
思路:
1.投票人数n和候选人都初始化0;
2.当n = 0,重新给候选人赋值;
3.遍历完后,候选人肯定为the majority element。(因为element>n/2)
<span style="white-space:pre"></span>
<span style="white-space:pre"></span>int majorityElement(vector<int>& nums) {<span style="white-space:pre"></span>int len = nums.size();int n = 0, candidate = 0;for (int i = 0; i < len; i++){if (n == 0){candidate = nums[i];n++;}else{if (candidate == nums[i])n++;else n--;}}if (n > 0)return candidate;}
0 0
- majority element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- majority element
- Majority Element
- Majority Element
- STL中set用法详解
- UVa 10689 - Yet another Number Sequence
- 1144: 组合的输出
- Java-Java语言基础
- Linux下通过crontab及expect实现自动化处理
- Majority Element
- Oracle APEX 4.2安装 与Oracle PL/SQL Gateway的配置
- 主从错误UUID
- 【数据结构】堆heap,Trie树,位图Bitmap
- Linux route 使用
- 蓝桥杯 VIP 基础练习 Huffuman树
- MySQL中整各种int类型的范围和存储大小
- 一句话记录:Winform编程中Label文本不显示“&”的奇葩问题
- Java基础学习——异常处理