My Solution


  • 0
    B

    '''
    #include <iostream>
    #include <vector>
    #include <sstream>
    #include <string>
    using namespace std;

    #define loop(i,a,b) for(int i = a; i <= b; i++)

    class Solution {
    public:
    int findMajorElement(vector<int> & vec);
    int checkMajority(vector<int> & vec, int majorElement);

    };

    Solution::int findMajorElement(vector<int> & vec){
    int majorIndex = 0;
    int majorElement = vec[majorIndex];
    int count = 1;

    loop(i, 1, vec.size() - 1){
        if (majorElement == vec[i]){
            count++;
        } else {
            count--;
        }
        if(count == 0){
            majorIndex = i;
            majorElement = vec[majorIndex];
            count = 1;
        }
    }
    
    return vec[majorIndex];
    

    }

    Solution::int checkMajority(vector<int> & vec, int majorElement){
    int count = 0;
    loop(i, 0, vec.size() - 1){
    if(vec[i] == majorElement){
    count++;
    }
    }
    if(count > vec.size()/2){
    return 1;
    } else {
    return -1;
    }

    }

    int main() {
    vector<int> vec;
    while(true) {
    string str;
    int value;
    getline(cin, str);
    istringstream stream(str);
    stream >> value;
    if (stream.fail()) {
    // cerr << "stringToInteger: Illegal integer format";
    break;
    }
    vec.push_back(value);
    }
    loop(i, 0, vec.size() - 1){
    cout << vec[i] << "\t";
    }
    cout << endl;
    Solution S;
    int majorElement = S.findMajorElement(vec);
    cout << "Major Element found " << majorElement << endl;
    int check = S.checkMajority(vec, majorElement);
    if(check == -1){
    cout << "No majority";
    } else {
    cout << "Major Element found as " << majorElement;
    }
    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.