C++ a Moore Majority Voting Solution using std::accumulate (two line)


  • 0
    O
        int times = 1; // a outer variable to hold the times
        return std::accumulate(nums.begin() + 1 , nums.end(), 
            nums.front(), 
            [&times](int m, int e) { // m is candidate, e is array element
                if (m == e) { times++; return m; } // increase times if matched, keep m
                if (times > 1) { times--; return m; } // decrease times, times still positive, keep m
                return e; // times - 1 == 0, change to e with times == 1.
            }
        );

Log in to reply
 

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