169. Majority Element
来源:互联网 发布:目标软件游戏 编辑:程序博客网 时间:2024/05/29 03:36
题目描述:
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.
解题思路:用一个pair来记录数组中的元素和出现的次数,然后筛选出其中出现次数超过一半的那个元素,即majority element。
代码:
class Solution {public: int majorityElement(vector<int>& nums) { list<pair<int, int> > L; list<pair<int, int> >::iterator i; for (int j = 0; j < nums.size(); j++) { i = L.begin(); while (i != L.end() && nums[j] > (*i).first) { i++; } if (i != L.end() && nums[j] == (*i).first) { (*i).second++; } else L.insert(i, pair<int, int>(nums[j], 1)); } i = L.begin(); int majority; int mid = nums.size()/2; while (i != L.end()) { if ((*i).second > mid) { majority = (*i).first; } i++; } return majority; }};
0 0
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- 进制转换的两种特殊方法
- 设计模式(多例)
- 括号匹配
- 文章标题
- 以前整理的网络上免费API接口
- 169. Majority Element
- GPL协议
- Python深度学习路线
- Error:CS0016: 未能写入输出文件“c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temp
- Hibernate (九)类的继承映射
- Quartz学习笔记(五)—— JobStore
- HDU2206 IP的计算
- CSS动画-2D、3D转换
- PHP-FPM运行原理以及相关配置