LeetCode #169: Majority Element
2016-09-22 11:07
423 查看
Problem Statement
(Source) Given an array of sizen, 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.
Solution
This problem can be solved usingBoyer–Moore majority vote algorithm(wiki).
There could be at most one majority element that appears more than
⌊ n/2 ⌋times in an array. And here we can assume that “the array is non-empty and the majority element always exist in the array“, so there is no need to do a further check of the occurrence of the possible candidate at the end of the major loop. The only candidate would be the only majority element we are trying to find.
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ x, count = None, 0 for i in xrange(len(nums)): if count == 0: x = nums[i] count = 1 elif nums[i] == x: count += 1 else: count -= 1 return x
Complexity analysis
- Time complexity: O(n), where n is the size of the given array.
- Space complexity: O(1), only a variable for counter and a variable for possible candidate are in need.
相关文章推荐
- LeetCode #229: Majority Element II
- 第三周项目3
- 王朝
- PyQt QCombobox设置行高
- 【codeforces】Misha and Changing Handles(映射+并查集)
- 体验复杂度 2种排序方法的运行时间比较
- dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()的关联 (三)
- ASP.NET的运行原理与运行机制
- MongoDB的基本配置与操作
- 第4周项目2 建设“单链表”算法库
- 【第四周项目3-单链表应用(2)】
- Java main方法
- 第4周项目2-建立“单链表”算法库
- 大家好,我是新人,请多关照
- Android tips(十一)-->android开发者需要了解的chrome插件
- VBA 操作 Excel 数据筛查
- BusyBox制作根文件系统(rootfs)
- UITableView UITableViewCell点击时,子view背景色消失
- 第四周-项目三 单链表应用(2)
- 爬虫:Scrapy16 - Spider Contracts