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
原创粉丝点击