169. Majority Element
2016-11-08 23:29
344 查看
题目:
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.
思路:
1. 由题目可知,输入不为空,且有且只有一个majority元素。
2. 我的思路是用一个map,标记每个值的出现次数,当遇到一个majority元素时,终止。(讨论区有其他更优化的算法)
代码:
int majorityElement(vector<int>& nums) {
map<int, int> res;
int size = nums.size();
cout<<size<<endl;
if (size == 1) return nums[0];
for(int num : nums){
if (res.find(num) == res.end()) res[num] = 1;
else{
res[num] += 1;
if (res[num] > size / 2) return num;
}
}
return 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.
思路:
1. 由题目可知,输入不为空,且有且只有一个majority元素。
2. 我的思路是用一个map,标记每个值的出现次数,当遇到一个majority元素时,终止。(讨论区有其他更优化的算法)
代码:
int majorityElement(vector<int>& nums) {
map<int, int> res;
int size = nums.size();
cout<<size<<endl;
if (size == 1) return nums[0];
for(int num : nums){
if (res.find(num) == res.end()) res[num] = 1;
else{
res[num] += 1;
if (res[num] > size / 2) return num;
}
}
return 0;
}
相关文章推荐
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 169 Majority Element
- Leetcode 169. Majority Element
- 169. Majority Element 破解思路
- LeetCode 169 -Majority Element ( JAVA )
- LeetCode OJ 169. Majority Element
- [Leetcode]169. Majority Element
- Leetcode 169. Majority Element (Easy) (cpp)
- LeetCode OJ-169. Majority Element
- LeetCode 169. Majority Element
- [LeetCode]169. Majority Element寻找数组中超过一半的那个数
- leetcode(169)Majority Element
- LeetCode 169. Majority Element
- 169. Majority Element
- 169. Majority Element
- 【Leetcode】169. Majority Element
- 169. Majority Element--寻找数组中出现次数超过一半的数据,229. Majority Element II--注意最后的检测
- [LeetCode]169. Majority Element
- 169. Majority Element
- 169. Majority Element