Answer the question
In order to leave comments, you need to log in
How to solve this corner case in the implementation of the algorithm for finding the majority element through divide-and-conquer?
Problem: I want to write an algorithm that would find the majority element of an array (or find its absence). Basically, I took the algorithm from LeetCode - Approach 5. This is what my code looks like:
long long majority_element(vector<long long>& a, unsigned long long lo, unsigned long long hi) {
if (lo == hi) return a[hi];
auto mid = (hi - lo) / 2 + lo;
auto left = majority_element(a, lo, mid);
auto right = majority_element(a, mid+1, hi);
if (left == right) return right;
auto l_cnt = count(a.begin(), a.end(), left);
auto r_cnt = count(a.begin(), a.end(), right);
if (r_cnt == l_cnt) return 0; // если вернулся ноль - мажоритарного нет
return l_cnt > r_cnt ? left : right;
}
512766168 717383758 5 126144732 5 573799007 5 5 5 405079772
Answer the question
In order to leave comments, you need to log in
Your code is wrong - you need to count() not on the entire array, but only between low and high.
Then the complexity of the whole algorithm will be O(n log n). What you have now done will have O(n^2) complexity.
There is no way to get rid of the calculation in this solution.
512766168in the first half, "5" will not be a majority element:
717383758
5
126144732
5
---------------
573799007
5
5
5
405079772
Is it possible to somehow fix this problem without stupid count() in case the element is majority in both halves?remove all duplicate elements from the input, remember the element with an odd number of repetitions and with the maximum number of duplicates and the number of such duplicates.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question