LintCode 47 主元素 II
来源:互联网 发布:淘宝手机壳评价 编辑:程序博客网 时间:2024/06/05 17:24
题目:majorityNumber
要求:
给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。
样例:
给出数组[1,2,1,2,1,3,3] 返回 1
算法要求:
要求时间复杂度为O(n),空间复杂度为O(1)。
解题思路:
在1的基础上,进行变型,增加一个m2,相当于最后剩下2个数进行计算,那么m1肯定就大于三分之一。
算法如下:
int majorityNumber(vector<int> nums) { // write your code here int size = nums.size(); int c1 = 1, c2 = 0; int m1 = nums[0]; int m2; for (int i = 1; i < size; i++) { if (nums[i] != m1) { m2 = nums[i]; c2 = 1; break; } } for (int i = 1; i < size; i++) { if (m1 == nums[i]) { c1 ++; } else if (m2 == nums[i]) { c2 ++; } else { c1--; c2--; if (c1 == 0) { m1 = nums[i]; c1 = 1; } else { m2 = nums[i]; c2 = 1; } } } c1 = 0; c2 = 0; for (int i = 0; i < size; i++) { if (nums[i] == m1) { c1++; } else if (nums[i] == m2) { c2++; } } return c1 > c2 ? m1 : m2; }
0 0
- LintCode 47 主元素 II
- [LintCode] 主元素 II Majority Number II
- *[Lintcode]Majority Number II 主元素 II
- Lintcode 主元素
- LintCode-主元素
- 主元素(LintCode)
- lintcode 主元素
- 主元素-----lintcode
- LintCode:主元素 III
- LintCode 主元素
- lintcode ----主元素
- LintCode(easy)主元素
- lintcode,主元素
- LintCode 主元素
- LintCode :主元素
- Lintcode 主元素 III
- LintCode 46 主元素
- [Lintcode]主元素
- 编译错误:error: invalid initialization of non-const reference of type ‘*&’ from a temporary of type
- CSS网页使用Font Awesome图标字体时,css定义 content 属性
- linux下redmine3.3迁移、升级、插件备忘录
- Qt两种设置Layout的方式有什么区别
- Spring-boot返回Json格式数据
- LintCode 47 主元素 II
- 如何获取和分析软件的非功能性需求
- 山东省第二届ACM B题题解
- UDP广播
- windows安装xampp时出现,unable to realloc xxxxxxxx bytes
- 深入理解Java内存模型(四)——volatile
- 简化激活Tensorflow环境的方法
- C#调用EasyPusher推送到EasyDarwin流媒体服务器直播方案及示例代码整理
- shiro的认证思路分析(即登录,流程)