[leetcode] 169. Majority Element
2016-03-26 17:26
393 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
这道题是找数组中个数超过一半的元素,题目难度为Easy。
最容易想到的办法是排序或用Hash Table统计元素个数,排序取中点元素的方法时间复杂度O(nlogn),Hash Table则需要额外的存储空间,这里介绍一下Majority Vote Algorithm,多数投票算法,时间复杂度O(n),空间复杂度O(1)。算法思路其实很简单,先上代码为敬。具体代码:class Solution {
public:
int majorityElement(vector<int>& nums) {
int major, count = 0;
for(int num:nums) {
if(count) {
if(major == num) ++count;
else --count;
}
else {
major = num;
++count;
}
if(count > nums.size()/2) break;
}
return major;
}
};遍历数组,如果计数器为0,将当前元素暂定为Majority
Element并将计数器置为1;如果计数器不为0,当前元素等于Majority Element时计数器加1,不等的话减1,这样如果存在超过一半的元素,最终记录下的Majority
Element就是它。
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
这道题是找数组中个数超过一半的元素,题目难度为Easy。
最容易想到的办法是排序或用Hash Table统计元素个数,排序取中点元素的方法时间复杂度O(nlogn),Hash Table则需要额外的存储空间,这里介绍一下Majority Vote Algorithm,多数投票算法,时间复杂度O(n),空间复杂度O(1)。算法思路其实很简单,先上代码为敬。具体代码:class Solution {
public:
int majorityElement(vector<int>& nums) {
int major, count = 0;
for(int num:nums) {
if(count) {
if(major == num) ++count;
else --count;
}
else {
major = num;
++count;
}
if(count > nums.size()/2) break;
}
return major;
}
};遍历数组,如果计数器为0,将当前元素暂定为Majority
Element并将计数器置为1;如果计数器不为0,当前元素等于Majority Element时计数器加1,不等的话减1,这样如果存在超过一半的元素,最终记录下的Majority
Element就是它。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解