LeetCoe:Majority Element
来源:互联网 发布:网络电信诈骗宣传片 编辑:程序博客网 时间:2024/05/16 23:01
Problem:
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的,有一点我们需要清楚,就是这样的元素在一个数组里面只能存在一个,明白这个问题,我们就好解决问题了
因为是需要考虑数字出现的次数,我们可以使用C++ STL中的关联容器map来解决,就是统计每个数字出现的次数,当出现一个map的value大于n/2返回key就行了。
int majorityElement(vector<int>& nums) { map<int, int> counts; int n = nums.size(); for (int i = 0; i < n; i++) if (++counts[nums[i]] > n / 2) return nums[i]; }
0 0
- LeetCoe: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
- majority element
- Majority Element
- HDU5869-Different GCD Subarray Query
- 第四届蓝桥杯第三题
- uva 11082Matrix Decompressing
- 关于正则表达式的一些知识和函数总结
- AspNetPager+mysql+数据集+ObjectDataSource+ListView 做的翻页
- LeetCoe:Majority Element
- laravel5.1启动详解
- Problem C: 整数的封装
- 基础练习 时间转换
- 热图的绘制
- mysql结果集
- cache与buffer的差别
- ios target -- weight todayWeight 开发
- CentOS6.5_64下 nginx+uwsgi+Python +多站点环境搭建