Leetcode:Majority Element
来源:互联网 发布:java写网络扫描器 编辑:程序博客网 时间:2024/06/05 23:51
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.
因为Majority Element出现的次数超过一半,所以只要将数组排序,排序后再数组中间的那个数就是Majority Element。
实现代码:
class Solution {public: int majorityElement(vector<int> &num) { sort(num.begin(),num.end()); int n=num.size(); return num[n/2]; }};上面代码的复杂度取决于排序。这里还有一种更好的方法,只需要遍历数组一遍,复杂度为O(n)。
class Solution {public: int majorityElement(vector<int> &num) { int vote = num[0]; int count = 1; int size = num.size(); //vote from the second number for( int i = 1; i < size; i++ ) { if( count == 0 ) { vote = num[i]; count++; } else if( vote == num[i] ) count++; else count--; } return vote; }};
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- Codeforces 490A Team Olympiad(水)
- android之绑定服务调用服务的方法
- HDU 4355 - Party All the Time(三分)
- 将jquery的datatables插件转为中文
- Bean property 'esyerDao' is not writable or has an invalid setter method. Does the parameter type of
- Leetcode:Majority Element
- 轮子---java返回image
- getSharedPreferences详解
- 责任链模式
- VMware converter使用指南
- HDU 1114 Piggy-Bank (完全背包)
- NEFU119 组合素数【算术基本定理】
- Scramble String (Java)
- codeforce Lexicographically Maximum Subsequence