OJ 169 Majority Element
题目要求: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.
我的解法:
1 int majorityElement(vector<int> &num) { 2 int key = num.back(); 3 int k = num.size(); 4 k--; 5 int i = k-1; 6 while (i >= k/2) 7 { 8 if (num[i] != key) 9 { 10 num[i] = num[k-1]; 11 k--; 12 key = num[k-1]; 13 k--; 14 i=k-1; 15 continue; 16 } 17 i--; 18 } 19 return key; 20 }
分析:首先要知道一个定理,如果一个序列中存在一个出现率大于1/2的元素,我们记为mE,那么如果去掉这个序列中的两个不相同的元素,新序列中一定存在一个出现率大于1/2的元素,依然是mE。
该算法最差情况需要在i指向第一个元素的时候,也就是算法的复杂度最差是O(n),最好的情况需要n/2。
这个问题还可以直接考虑,通过map来计数,来获取所求的元素。代码如下:
1 int majorityElement(vector<int> &num) { 2 map<int, int> count; 3 for (int i : num) 4 { 5 if (++count[i] >= num.size() / 2) 6 { 7 return i; 8 } 9 } 10 }
转载于:https://www.cnblogs.com/charleschiu/p/4338250.html
OJ 169 Majority Element相关推荐
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
题目: Given an array of size n, find the majority element. The majority element is the element that ap ...
- leetcode讲解--169. Majority Element
169. Majority Element Given an array of size n, find the majority element. The majority element is t ...
- [Easy] 169. Majority Element
169. Majority Element Given an array of size n, find the majority element. The majority element is t ...
- [勇者闯LeetCode] 169. Majority Element
[勇者闯LeetCode] 169. Majority Element Description Given an array of size n, find the majority element. ...
- leetcode 169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appear ...
- 【LeetCode】169. Majority Element
原题链接:https://leetcode.com/problems/majority-element/description/ 要求: Given an array of size n, find ...
- Leetcode - 169. Majority Element (多数投票问题)
Given an array of size n, find the majority element. The majority element is the element that appear ...
- 【LeetCode从零单排】No.169 Majority Element(hashmap用法)
题目 Given an array of size n, find the majority element. The majority element is the element that app ...
- [LeetCode]: 169: Majority Element
题目: Given an array of size n, find the majority element. The majority element is the element that ap ...
最新文章
- Windows下Python环境搭建
- 服务器write后客户端响应,客户端解析服务器响应的multipart/form-data数据
- swift golang java,解决两数之和 (Javascript, Java, C#, Swift, Kotlin, Python,C++, Golang)
- docker-compose常用命令整理及使用示例
- 在window10 WSL 中编译 OpenJDK13
- vba 自动排序_给VBA字典键值排序,并提取需要的数据
- Mac安装sqlmap【亲测有用】
- 案例:Oracle 11g RAC 数据库连接数过高处理办法
- 不定高宽的元素居中的方法
- 2021年中国再生纱市场趋势报告、技术动态创新及2027年市场预测
- OFF文件格式_拔剑-浆糊的传说_新浪博客
- 学计算机专业1050显卡够不够,gtx1050显卡性能怎么样
- linux内存管理笔记(十一)---CMA
- 公钥证书的颁发和使用
- 【Cheatsheet】详解git的各种操作
- MATLAB中均值、方差、标准差、协方差、相关性的计算
- HTML jQuery实现点赞功能(模仿CSDN的样式)
- SAP 采购订单收货时报错:对于采购订单xxxx无收货可能
- 读《杨振宁传》---谈taste
- C#设计模式——组合模式(Composite Pattern)