leetcode 169. 多数元素
2020-03-15 18:22
549 查看
leetcode 169. 多数元素
题目详情
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
*你可以假设数组是非空的,并且给定的数组总是存在多数元素。
- 示例 1:
输入: [3,2,3]
输出: 3- 示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
我的代码
class Solution { public: int majorityElement(vector<int>& nums) { int len = nums.size(); if ((len == 1) || (len == 2)) { return nums[0]; } map<int, int> index; for (int num: nums) { if (index.count(num) == 0) { index[num] = 1; continue; } index[num] += 1; } for (auto iter = index.begin(); iter != index.end(); ++iter) { if (iter->second > len / 2) { return iter->first; } } return nums[0]; } };
我的成绩
执行结果:通过
执行用时 :28 ms, 在所有 C++ 提交中击败了47.36%的用户
内存消耗 :20.4 MB, 在所有 C++ 提交中击败了5.28%的用户
一些想法
- 本题最简单的思路莫过于先排序,然后返回处于中间的数字,但如此做下来效果并不是很理想。
- 改进想法是先遍历数组,然后读入map记录每个元素出现的次数,再遍历map。
执行用时为 4 ms 的范例
class Solution { public: int majorityElement(vector<int>& nums) { int num=nums[0],count=1; for(int i=1;i<nums.size();i++){ if(nums[i]==num) count++; else{ count--; if(count<0){ num=nums[i]; count=1; } }} return num; } };
思考
可以看出,范例的想法非常巧妙,因为多数元素个数大于len / 2的性质,所以在进行记数后的数字必然是多数元素。
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- leetcode-169 多数元素 Python
- LeetCode 题解 169. Majority Element(查找多数元素)
- LeetCode Problem 169: Majority Element查找多数元素
- [LeetCode Problem]169:Majority Element查找多数元素
- LeetCode-169:Majority Element (数组中的多数元素)
- [LeetCode] 169. Majority Element 多数元素
- [LeetCode]169. Majority Element(多数元素)
- LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)
- leetcode_169(主元素查找)
- LeetCode 169 Majority Element(主要元素)(vector、map)
- 169. Majority Element (寻找多数元素)
- [LeetCode-169] Majority Element(找出数组中超过一半元素)
- [LeetCode] 229. Majority Element II 多数元素 II
- 【LeetCode-面试算法经典-Java实现】【169-Majority Element(主元素)】
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- Leetcode:169. Majority Element(找到数组中出现次数最多的元素)
- 169. Majority Element 查找多数元素
- LeetCode探索之旅(40)-169最大元素
- Java数组(算法169,747):多数元素,至少是其他数字两倍的最大数
- leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)