fork download
  1. /*Write a program to take an integer array nums of size n, and print the majority element. The majority element is
  2. the element that appears strictly more than ⌊n / 2⌋ times. Print -1 if no such element exists. Note: Majority
  3. Element is not necessarily the element that is present most number of times.*/
  4. #include <stdio.h>
  5.  
  6. int main() {
  7. int n;
  8. scanf("%d", &n);
  9.  
  10. int nums[n];
  11. for (int i = 0; i < n; i++) scanf("%d", &nums[i]);
  12.  
  13. // Boyer–Moore Voting
  14. int candidate = 0, count = 0;
  15. for (int i = 0; i < n; i++) {
  16. if (count == 0) candidate = nums[i];
  17. count += (nums[i] == candidate) ? 1 : -1;
  18. }
  19.  
  20. // Verify candidate is actually majority
  21. count = 0;
  22. for (int i = 0; i < n; i++)
  23. if (nums[i] == candidate) count++;
  24.  
  25. if (count > n / 2) printf("%d", candidate);
  26. else printf("-1");
  27.  
  28. return 0;
  29. }
  30.  
Success #stdin #stdout 0s 5320KB
stdin
7
2 2 1 2 3 2 2
stdout
2