QUESTION

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.

FIRST TRY

每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。

class Solution {
public:
int majorityElement(vector<int> &num) {
int ret;
int nTimes = ;
for(int i = ; i < num.size(); i++){
if(nTimes == )
{
ret = num[i];
nTimes++;
}
else if(ret == num[i]) nTimes++;
else nTimes--; //2 different number, delete
}
return ret;
}
};

Result: Accepted

可扩展到⌊ n/k ⌋的情况,每k个不同的element进行成对删除。

最新文章

  1. pptpvpn 连接后 无法上外网
  2. uva133-S.B.S.
  3. LINQ TO DATATABLE/DATASET基本操作之-简单查询
  4. 李洪强iOS开发Swift篇---11_变量&amp;常量&amp;元组
  5. LintCode-编辑距离
  6. redis作为mysql的缓存服务器(读写分离) (转)
  7. JS达到Web指定保存的和打印功能的内容
  8. 【高德地图API】从零开始学高德JS API(二)地图控件与插件——测距、圆形编辑器、鼠标工具、地图类型切换、鹰眼鱼骨
  9. Cdoefroces #354
  10. 分享几个 git 的使用场景
  11. 【easy】power of 2,3,4
  12. (二)类数组对象HTMLCollection
  13. iis默认文档
  14. TypeScript作业
  15. DOS下读取PCI配置空间信息的汇编程序(通过IOCF8/IOCFC)
  16. 30 C? Go? Cgo!
  17. MySQL启动项提权
  18. Boost智能指针——weak_ptr
  19. Django ORM 查询
  20. [设计模式-行为型]状态模式(State)

热门文章

  1. Unreal Engine 4(虚幻UE4)GameplayAbilities 插件入门教程(五)技能属性集(AttributeSet)
  2. php session保存到memcache或者memcached中
  3. Logistic回归的两种形式y=0/1,y=+1/-1
  4. CSS border-right-style属性设置元素的右边框样式
  5. Python - Django - 登录页面
  6. python2-python3字符串
  7. 2013年6月编程语言排行榜,C语言位据第一位
  8. 75. ID重新走过,备份表
  9. https Configure a Spring Boot app for HTTPS on Amazon AWS.
  10. leetcode235