leetcode 169 Majority Element
来源:互联网 发布:ubuntu 14.04使用手册 编辑:程序博客网 时间:2024/04/29 06:19
题目描述:
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.
找到这个数组中出现次数超过n/2次的元素,假设这个元素一定是存在的。
一个简单的方法就是排序后找中间的元素,代码如下:
class Solution {public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; }};
还有一种方法就是分而治之,每次将这个数组分为两半分别去找两边的主元素,若两边的主元素不同则利用count方法比较出现次数,时间复杂度略优
class Solution {public: int majorityElement(vector<int>& nums) { return divideMajor(nums, 0, nums.size() - 1); } int divideMajor(vector<int>& nums, int begin, int end) { if (begin == end) { return nums[begin]; } int leftM = divideMajor(nums, begin, (begin + end) / 2); int rightM = divideMajor(nums, (begin + end) / 2 + 1, end); if (leftM == rightM) { return leftM; } if (count(nums.begin() + begin, nums.begin() + end+1, leftM) < count(nums.begin() + begin, nums.begin() + end+1, rightM)) { return rightM; } else { return leftM; } }};
阅读全文
0 0
- leetcode 169-Majority Element
- [leetcode 169] Majority Element
- leetCode#169 Majority Element
- Leetcode-169Majority Element
- LeetCode 169: Majority Element
- [LeetCode][169][Majority Element]
- LeetCode 169 Majority Element
- Majority Element leetcode[169]
- Leetcode[169]-Majority Element
- leetcode[169]:Majority Element
- leetcode-169-Majority Element
- leetcode 169: Majority Element
- Leetcode # 169 Majority Element
- [Leetcode]#169 Majority Element
- LeetCode 169: Majority Element
- 【LEETCODE】169-Majority Element
- 【LeetCode】169Majority Element
- Leetcode #169 Majority Element
- linux下如何用GDB调试c++程序
- 管理选择器结果
- 深度探索C++ 对象模型【第七章1】
- Dubbox学习笔记
- uboot 命令
- leetcode 169 Majority Element
- Oracle:数据库对象(一)
- C语言 素数环
- 以太网数据的封装
- xilinx 约束文件
- jQuery对节点答操作
- Could not instantiate bean class [javax.servlet.ServletContext]: Specified class is an interface
- hihocoder 1098(kruskal)
- 分布式系统sheepdog之dog执行流程