博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】169 - Majority Element
阅读量:7041 次
发布时间:2019-06-28

本文共 1219 字,大约阅读时间需要 4 分钟。

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.

 Solution 1: 使用map计数

1 class Solution { 2 public: 3     int majorityElement(vector
& nums) {    //runtime:32ms 4 map
nums_count; 5 vector
::iterator iter=nums.begin(); 6 7 while(iter!=nums.end()){ 8 ++nums_count[*iter]; 9 iter++;10 }11 12 int n=nums.size();13 14 map
::iterator ite=nums_count.begin();15 //int max=ite->second;16 while(ite!=nums_count.end()){17 if(ite->second>n/2){18 return ite->first;19 }20 ite++;21 }22 }23 };

Solution 2: 每找出两个不同的element就成对删除,最后可能剩两个元素或一个元素,必定都是所求

 

1 class Solution { 2 public: 3     int majorityElement(vector
& nums) { //runtime: 20ms 4 int count=0; 5 int ret; 6 for(int i=0;i

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

转载于:https://www.cnblogs.com/irun/p/4722615.html

你可能感兴趣的文章
[转]大整数算法[11] Karatsuba乘法
查看>>
boost初探
查看>>
viewpager显示图片的Adapter
查看>>
(链表)链表倒序
查看>>
4.使用 WSDL 指定的标准 SOAP 消息格式
查看>>
HTML基础第五讲---控制表格及其表项的对齐方式
查看>>
创建数据表空间
查看>>
unity android相互调用
查看>>
未备案域名打开国内服务器上的网站(绑定国外空间并判断url后跳转引用)
查看>>
原生js封装ajax,实现跨域请求
查看>>
类和对象
查看>>
判断整数的奇偶
查看>>
第六课:高压击穿和闪电
查看>>
洛谷P4207 [NOI2005]月下柠檬树(计算几何+自适应Simpson法)
查看>>
#6432. 「PKUSC2018」真实排名(组合数学)
查看>>
MYSQL数据库设计规范11111
查看>>
数据库表与表的连接方式
查看>>
[BJOI2019] 光线
查看>>
装饰模式
查看>>
296. Best Meeting Point
查看>>