[勇者闯LeetCode] 169. Majority Element
[勇者闯LeetCode] 169. Majority Element
Description
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.
Information
- Tags: Array | Divide and Conquer | Bit Manipulation
- Difficulty: Easy
Solution
利用位操作,先初始化输出元素为首元素,其出现次数cnt
为1,扫描数组,若当前元素与输出元素相同,则cnt
加1;否则cnt
减1,且cnt
为0时,将输出元素重置为当前元素,出现次数cnt
重置为1,扫描结束后输出元素将是数组中出现次数超过一半的那个元素。
C++ Code
class Solution {
public:int majorityElement(vector<int>& nums) {int ans = nums[0], cnt = 1;for (const auto& num : nums) {if (num == ans) {++cnt;}else {--cnt;if (cnt == 0) {ans = num;cnt = 1;}}}return ans;}
};
[勇者闯LeetCode] 169. 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
Given an array of size n, find the majority element. The majority element is the element that appear ...
- 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
题目: Given an array of size n, find the majority element. The majority element is the element that ap ...
- [swift] 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
Given an array of size n, find the majority element. The majority element is the element that appear ...
- LeetCode 169 Majority Element(Majority Voting Algorithm)
Majority Element Given an array of size n, find the majority element. The majority element is the el ...
- leetcode讲解--169. Majority Element
169. Majority Element Given an array of size n, find the majority element. The majority element is t ...
- [勇者闯LeetCode] 1. Two Sum
[勇者闯LeetCode] 1. Two Sum Description Given an array of integers, return indices of the two numbers s ...
最新文章
- VC++ 给选项卡控件添加不同图标
- js小记 function 的 length 属性
- 你真的了解过Lucene吗?
- hive外部表改为内部表_hive内部表外部表介绍
- 远控免杀专题(16)-Unicorn免杀
- windows游戏编程_苹果的Mac和微软的Windows该如何选择?
- Elasticsearch 性能监控2(五种常见问题的解决办法)
- 启动tomcat后无法访问
- 邮箱服务器退回,发出去的邮件为什么被退回?
- 软件工程--结对第二次作业
- JavaWeb汽车商城项目
- 强化学习平台安装 Mujoco、mujoco-py、gym、baseline
- 常见HTTP状态码大全
- matlab功能特点,MATLAB的特点及应用领域
- 在本地电脑将ip与名字相关联
- 什么是数据科学?数据科学的基本内容
- 物理化学笔记(1) 量子化学基础
- L1 Cache、L2 Cache、L3 Cache说明
- blur事件和ajax,js关于blur事件阻塞click事件
- c加加语言三体问题,既然三体问题无法精确计算,行星的运行是否也不能精确?...
热门文章
- 数据库对比:选择MariaDB还是MySQL?
- 设计模式(5)--三种工厂模式(披萨店)
- iOS里很简单的推送,移动端。
- 希望聊城营养师协会网站越来越好。
- 《贵州省大数据发展报告(2016)》白皮书发布
- 别人以为的在家办公 VS 实际上的在家办公
- Windows10系统22H2安装AX201蓝牙出现叹号问题解决思路(iPhone13联机同样解决)
- 随身WiFi部署个人博客:从入门到入土
- windows7桌面不显示计算机,win7电脑开机后不显示桌面 - 电脑 - 办公IT技术网 bangongit.com...
- 作为中国站长,你能做到20个…