fork(4) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. //Find Majority element i.e. the element that occurs more than 1/2 of the array
  5. // Worst Case Complexity : O(n)
  6. template <typename DataType>
  7. DataType FindMajorityElement(std::vector<DataType> arr) {
  8. // Modified BOYERS ALGORITHM with forward and reverse passes
  9. // Count will stay positive if there is a majority element
  10. auto GetMajority = [](auto seq_begin, auto seq_end) -> DataType{
  11. int count = 1;
  12. DataType majority = *(seq_begin);
  13. for (auto itr = seq_begin+1; itr != seq_end; ++itr) {
  14. count += (*itr == majority) ? 1 : -1;
  15. if (count <= 0) { // Flip the majority and set the count to zero whenever it falls below zero
  16. majority = *(itr);
  17. count = 0;
  18. }
  19. }
  20. return majority;
  21. };
  22. DataType majority1 = GetMajority(arr.begin(), arr.end());
  23. DataType majority2 = GetMajority(arr.rbegin(), arr.rend());
  24. int maj1_count = 0, maj2_count = 0;
  25. // Check if any of the the majority elements is really the majority
  26. for (const auto& itr: arr) {
  27. maj1_count += majority1 == itr ? 1 : 0;
  28. maj2_count += majority2 == itr ? 1 : 0;
  29. }
  30. if (maj1_count >= arr.size()/2)
  31. return majority1;
  32. if (maj2_count >= arr.size()/2)
  33. return majority2;
  34. // else return -1
  35. return -1;
  36. }
  37.  
  38. int main() {
  39. using namespace std;
  40. std::cout << FindMajorityElement(std::vector<int> { 1, 10, 2, 10, 1, 10, 4, 10, 5, 10 }) << endl;
  41. std::cout << FindMajorityElement(std::vector<int> { 10, 1, 10, 2, 10, 1, 10, 4, 10, 5 }) << endl;
  42. std::cout << FindMajorityElement(std::vector<int> { 1, 2, 1, 10, 10, 10, 10, 4, 10, 5 }) << endl;
  43. std::cout << FindMajorityElement(std::vector<int> { 1, 1, 1, 10, 10, 10, 10, 10, 5, 4 }) << endl;
  44. std::cout << FindMajorityElement(std::vector<float> { 1.0f, 1.0f, 1.0f, 10.f, 10.0f, 10.0f, 10, 10, 5, 4 }) << endl;
  45. return 0;
  46. }
  47.  
  48.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
10
10
10
10
10