leetcode--169. Majority Element
来源:互联网 发布:读懂中国经济数据 上 编辑:程序博客网 时间:2024/04/27 19:40
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.
Credits: Special thanks to @ts for adding this problem and creating all test cases.
思路: 1. 有题目可以知道,所求的元素的数目大于⌊ n/2 ⌋,也就意味着,且该元素是存在的。
2. 通过每寻找到两个不同的元素的时候,就一块删除掉,剩下最后的就是所求的元素。(因为该元素数目大于⌊ n/2 ⌋该,也就是一半,所以一次 删除两个不同元素最后就是目标元素)
具体代码实现如下:
class Solution {public: int majorityElement(vector<int>& nums) { int majority = 0; int count = 0; for(int i = 0; i < nums.size(); i++){ if(count == 0){ majority = nums[i]; count = 1; } else{ if(nums[i] == majority)count ++; else count --; } } return majority; }};
0 0
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- [leetcode] 169.Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- [LeetCode]169. Majority Element
- 【LeetCode】169. Majority Element
- leetcode 169. Majority Element
- leetcode 169. Majority Element
- [leetcode] 169. Majority Element
- 面试笔记2
- A+B for Input-Output Practice (V)
- MapReduceOnYarn(iMapReduce在Yarn执行的流程分享)
- MQTT---HiveMQ源码详解(十四)Persistence-LocalPersistence
- nodejs + redis/mysql 连接池问题
- leetcode--169. Majority Element
- Mysql 服务无法启动 服务没有报告任何错误
- RPG开发日记
- Add Two Numbers
- Nanopi 2,装机开始到第一个实验,串口通信
- 10023---Linux下which、whereis、locate、find命令的区别
- 多线程_多线程总结
- php笔记
- pat 关键活动