PIQ03: Find Majority Element in an Array
来源:互联网 发布:淘宝实体微商女装货源 编辑:程序博客网 时间:2024/05/18 00:30
Problem Statement
Given an array of size n, find the element which occurs more than n/2 times. This element is called Majority Element. If not found, return null.
Approach 1: Use a counter
def majority_element1(arr): """ Time complexity: O(n). Space complexity: O(n). """ if not arr: return None from collections import Counter cnt = Counter(arr) most_common_element, count = cnt.most_common(1)[0] if count > (len(arr) >> 1): return most_common_element else: return None
The space complexity of the proposed algorithm can be further optimised to O(1)
。
Approach 2: Boyer–Moore majority vote algorithm
Algorithm Link
def majority_element(arr): """ Time complexity: O(n). Space complexity: O(1). """ if not arr: return None candidate, counter = arr[0], 0 for ele in arr: if counter == 0: candidate, counter = ele, 1 else: if candidate == ele: counter += 1 else: counter -= 1 if counter == 0: return None counter = 0 for ele in arr: counter += (ele == candidate) if counter > (len(arr) >> 1): return candidate else: return None
0 0
- PIQ03: Find Majority Element in an Array
- 【LeetCode】169. Majority Element Majority Element Given an array of size n, find the majority eleme
- find ith smallest element in an array
- Given an array of size n, find the majority element. The majority element is the element that appear
- Find the kth largest element in an unsorted array
- 153. Find Minimum in Rotated Sorted Array\229. Majority Element II\Moore's voting algorithm
- Find the maxest element of an array
- Find duplicates in an array
- LeetCode[Array]: Majority Element
- [leetcode][array] Majority Element
- [Array]Majority Element
- Finding Second Minimum element in an Array
- Kth Largest Element in an Array
- Leetcode Kth Largest Element in an Array
- Kth Largest Element in an Array
- Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- Implement Trie (Prefix Tree)
- Super Pow
- 确定管理幅度:形成组织层级
- PageControll加入子窗体
- storm流式大数据处理流行吗
- PIQ03: Find Majority Element in an Array
- 权利及其类型
- 利用Cydia Substrate进行Android Native HOOK
- [POI2007]砝码Odw
- 部门管理者通常拥有的权力
- Vuforia + Unity3d SDK开发-hello world
- INSERT FIRST和INSERT ALL
- 【9702】黑白棋的移动
- 会声会影X7安装中的问题