Leetcode: Majority Element
2015-08-27 02:58
274 查看
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.
Show Tags
Show Similar Problems
Solution
Analysis
refer to hereMoore voting algorithm.
We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
1. If the counter is 0, we set the current candidate to x and the counter to 1.
2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
Code
[code]class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ most, count = nums[0], 1 for ind in range(1,len(nums)): if nums[ind]==most: count += 1 else: if count==0: most = nums[ind] else: count -= 1 return most
相关文章推荐
- hdoj4539郑厂长系列故事——排兵布阵【状压dp】
- Centos7安装及使用webbench进行并发测试
- Linux用户和组管理
- C++ Primer : 第十二章 : 动态内存之allocator类
- LeetCode Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- Python初学(6)——Python的函数
- 笔试题整理
- 根据user stack 数据分析函数调用栈
- 进程管理
- Leetcode: Intersection of Two Linked Lists
- TCPServer
- 字节型TCP协议解析
- 华为上机题7(四则运算)
- 单例模式在android中的应用
- 扩展Tomcat支持OSGi应用服务
- jmeter 树结构返回乱码解决
- 单例模式在android中的应用
- Leetcode: Number of Bits
- 面试题:寻找第N个丑数