主元素
来源:互联网 发布:大数据技术与城市规划 编辑:程序博客网 时间:2024/05/16 19:57
问题描述:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
给出数组[1,1,1,1,2,2,2],返回 1
与落单的数解题思路相似,不同的是要找从比较的数开始,第n/2个仍是该数。
代码:
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
int n=nums.size();
if(n==1) return nums[0];
else
{
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++)
{ if(nums[i]==nums[i+n/2])
{ return nums[i];
break;
}
}
}
}
};
感悟:
算明白相同的数的个数,开始多想了。
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素
- 主元素、主元素II、主元素III
- python_lintcode_47主元素_47主元素 II_48主元素 III
- 主元素II和主元素III
- 寻找多数元素/主元素问题
- 寻找多数元素(主元素)
- 找主元素
- 卸载驱动出现:rmmod: can't change directory to '/lib/modules': No such file or directory
- 整理GridControl层级表格及按钮列
- Python 列表推导
- Robot Framework如何判断Android屏幕是否含有某个控件
- AWS EC2 shadowsocks服务端搭建
- 主元素
- 开发者需要知道的十几个网站
- c++ log4cxx自定义日志存放目录
- Java中String字符串转整型或浮点型
- Java入门记(一):折腾HelloWorld
- 97.二叉树的最大深度
- 为什么这么多事??!!!!
- AngualrJs 最新 文件图片上传教程0:Client-module
- C语言集成开发环境vs2017的使用技巧之修改快捷键