Leetcode 169
2016-03-30 11:41
302 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int j=1,m,i,z;
if(nums.size()==1 || nums.size()==2)
return nums[0];
else
{
sort(nums.begin(),nums.end());
for(i=0;i<nums.size()-1;i++)
{
if(nums[i]==nums[i+1])
j++;
else
{
if(j>(nums.size()/2))
return nums[i];
else
j=1;
}
}
if(i=nums.size()-2)
return nums[nums.size()-2];
}
}
};
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int j=1,m,i,z;
if(nums.size()==1 || nums.size()==2)
return nums[0];
else
{
sort(nums.begin(),nums.end());
for(i=0;i<nums.size()-1;i++)
{
if(nums[i]==nums[i+1])
j++;
else
{
if(j>(nums.size()/2))
return nums[i];
else
j=1;
}
}
if(i=nums.size()-2)
return nums[nums.size()-2];
}
}
};
相关文章推荐
- 柳峰微信公众平台开发教程企业号修改篇(AccessToken篇)
- C#中的泛型
- 多重循环优化
- 柳峰微信公众平台开发教程企业号修改篇(AccessToken篇)
- git使用教程——Mob分享总结
- MySQL 常用的命令
- DataBinding 再也不用写findviewbyId了
- Service--简单学习
- 35 个 jQuery 小技巧
- Camel——涨知识了,骆驼命名法
- IOS开发-UI学习-沙盒机制&文件操作
- iOS开发常用的资源和资料
- TableView Cell
- Android用户注册界面
- PHP中的函数-- foreach()的用法详解
- simpleCursorAdapter中的listview获取内容
- Tomcat ( 单机多 Tomcat 并存 )
- extjs控制器调用其他视图的函数实现控件赋值。
- HTML的各个标签的默认样式有哪些
- dubbo简述