Majority element | Divide and Conquer | Leetcode 169

preview_player
Показать описание
Python code

Explanation Pic

Problem Link
Рекомендации по теме
Комментарии
Автор

def divide_conquer(nums, l, r) :
if l == r:
return (nums[l], 1)
mid = (l + r) // 2
f = divide_conquer(nums, l, mid)
s = divide_conquer(nums, mid+1, r)
## not the same majority substract the extra
if f[0] != s[0] :
if f[1] > s[1] :
return (f[0], f[1]-s[1])
else :
return (s[0], s[1]-f[1])
else :
return (f[0], s[1]+f[1])
# print(divide_conquer(nums))
n = len(nums)
return divide_conquer(nums, 0, n-1)[0]
Here is the code in python based on your explanation and it works. Thanks

rafik
Автор

Thankyou! Your recursion tree is very clear for me understand this algo!

harrybi
Автор

why can't we make a hash map and update the count in the hash map with a key which is coming in each iteration of array !!
and iterate the hash to find the max occiring element?

pravinpoudel
Автор

wtf was that where is code . why you wrote leetcode 169

gursimransingh