leetcode_169. Majority Element
来源:互联网 发布:快递单号记录软件 编辑:程序博客网 时间:2024/06/02 13:14
题目:
Given an array of size n, find the majority element. The majority element is the element that appearsmore than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
思想很简单,就是超过一半的那个数输出出来。一想肯定是要计数了。如果用两个for那就复杂度是O(n^2)了,那就用一个Map,给每个数都计数,然后当大于一半的时候就输出。这时的复杂度是O(n)。
贴代码:
class Solution {public: int majorityElement(vector<int>& nums) { map<int, int>hash; int size = nums.size(); for(int i = 0; i < size; ++i){ hash[nums[i]]++; if(hash[nums[i]] > size/2){ return nums[i]; } } }};
咦,等等,这个题是分治算法中的一道,为啥没用分治算法。
思考,如何用分治算法呢。。想了想,难道是用分治排序,然后因为有大于一半的,所以中位数一定就是大于一半的那个值?用到了数学知识。但这个分治有点强行加上去啊。。
这周有点忙,先做这一道简单的,有空再做其他的。
0 0
- leetcode_169. Majority Element
- leetcode_169. Majority Element
- 2017-09-12 LeetCode_169 Majority Element
- majority element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- 华为OJ 字符串运用-密码截取
- POJ1338 Ugly Numbers
- Probabilistic decoder, Bayesian neural network, Probabilistic encoder
- java学习
- 通过jdbc访问mysql数据库的具体过程及简单查询
- leetcode_169. Majority Element
- leetcode#121#122#123 Best Time to Buy and Sell Stock
- Mysql5.7安装初始化
- Linux基本分区管理
- Android 6.0.1选取本地图片操作时报No Activity found to handle intent错误
- drupal8 url link
- Nginx的安装
- HTTP相关知识点总结
- Final Cut Pro X 学习笔记