LeetCode 169 Majority Element(主要元素)(vector、map)
2016-01-12 15:48
393 查看
翻译
[code]给定一个长度为n的数组,找出主要的元素。 所谓主要的元素是指的出现次数超过⌊ n/2 ⌋次的元素。 你可以假定这个数组是非空的,并且“主要元素”一定是存在的。
原文
[code]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这东西,直接是所有序列中最长的。[code]1,2,2,3,3,3,3,3,4,4 --> 1-1 2-2 3-5 4-2
看到了键值对,想到了基本的map,还有些复杂的容器我就用的不太熟悉了……
在下面的代码这两个,我首先定义了element元素,然后用range-for从nums中便利所有的元素:
[code]1)如果在map中找不到这个元素,就添加进去; 2)如果找到了,将其出现的个数加上1。如果当前的长度大于最大的长度,则进行一些列操作,并将max设置为当前的n,以便于后面的返回。
调试之后发现还有nums长度为1的情况,于是在开头加上一个判断。
[code]int majorityElement(vector<int>& nums) { if (nums.size() == 1) return nums[0]; map<int, int> element; int max = 0, maxLen = 0; for (auto n : nums) { if (element.find(n) == element.end()) { element.insert(map<int, int>::value_type(n, 1)); } else { element += 1; if (element >= maxLen) { maxLen = element ; max = n; } } } return max; }
代码
[code]class Solution { public: int majorityElement(vector<int>& nums) { if (nums.size() == 1) return nums[0]; map<int, int> element; int max = 0, maxLen = 0; for (auto n : nums) { if (element.find(n) == element.end()) { element.insert(map<int, int>::value_type(n, 1)); } else { element += 1; if (element >= maxLen) { maxLen = element ; max = n; } } } return max; } };
相关文章推荐
- 电子时钟--Datetime.now
- 类的生命周期
- 命令行中的数据科学_笔记1
- SQL Server 2008 误删除数据的恢复
- ViewController的生命周期
- Javascript学习笔记2——在html中使用js
- PLSQL的安装步骤
- html5的页面缓存和本地数据存储支持
- 某某业务数据库RMAN备份实例记录
- Android开发
- 快速理解Kafka分布式消息队列框架
- 【java基础 2】J2EE的13种规范
- js 基本类型和引用类型 变量复制 参数传递
- Android中通过反射和getResource()得到id的方式去改变View的显示效果
- JAVA字符串
- Android 中的SIP协议
- 美国海军的事后回顾
- 【java 理论篇 2】J2EE的13种规范
- C#ref 使用
- 建索引的几大原则