fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int majority_element(vector<int> &nums){
  5. int cur_major;
  6. int cur_major_count = 0;
  7.  
  8. for (int num: nums){
  9. if(cur_major_count== 0){
  10. cur_major = num;
  11. cur_major_count++;
  12. } else{
  13. if(cur_major == num){
  14. cur_major_count++;
  15. } else {
  16. cur_major_count --;
  17. }
  18. }
  19. }
  20.  
  21. return cur_major;
  22. }
  23.  
  24. int main(){
  25. vector<int> num_in;
  26. string num_in_str;
  27. int temp_num;
  28.  
  29. cout << "Enter the array. Each element separated by a comma and a space. (e.g. 2, 2, 1, 1, 2, 2)\n> " ;
  30. getline(cin, num_in_str);
  31. stringstream ss(num_in_str);
  32.  
  33. while(ss >> temp_num){
  34. num_in.push_back(temp_num);
  35.  
  36. if(ss.peek() == ' ' || ss.peek() == ','){
  37. ss.ignore();
  38. }
  39. }
  40.  
  41. cout << "Majority element: " << majority_element(num_in);
  42. }
Success #stdin #stdout 0.01s 5316KB
stdin
2, 2, 1, 1, 2, 2, 1, 2, 2
stdout
Enter the array. Each element separated by a comma and a space. (e.g. 2, 2, 1, 1, 2, 2)
> Majority element: 2