169. Majority Element
来源:互联网 发布:第三类顶级域名 编辑:程序博客网 时间:2024/06/11 04:05
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.
题目含义:
给定大小为n的数组,找到多数元素。多数元素是出现次数以上 的元素⌊ n/2 ⌋。
您可以假定该数组不为空,并且多数元素始终存在于数组中。
思想:可以使用莫尔德投票算法
算法描述
算法在局部变量中定义一个序列元素(m)和一个计数器(i),初始化的情况下计数器为0. 算法依次扫描序列中的元素,当处理元素x的时候,如果计数器为0,那么将x赋值给m,如果计数器不为0,那么将序列元素m和x比较,如果相等,那么计数器加1,如果不等,那么计数器减1。处理之后,最后存储的序列元素(m),就是这个序列中最多的元素。
C++ AC代码:时间o(n) 空间o(1)
class Solution {public: int majorityElement(vector<int>& nums) { int len = nums.size(); int variable; int times=0; for(int i=0;i<len;i++){ if(times==0){ variable=nums[i]; } if(variable==nums[i]) times++; else times--; } return variable; }};
阅读全文
0 0
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- CTF笔记
- CSS Media Queries响应式布局
- 6月8日,每日20行。
- 剑指offer——斐波那契数列,跳台阶、变态跳台阶、矩形覆盖
- 设计具有社交属性的产品方法步骤详解
- 169. Majority Element
- nodemcu 读写实时时钟DS1307 用lua
- MySQL数据库中添加用户,用户授权,删除用户以及修改用户的密码
- 31. Next Permutation
- java初步--冒泡
- 点分治
- Android之Activity
- MVC,MVP,MVVM的区别和联系
- python 获取某个目录字段下的子目录或文件