Did I hit a bug or some hidden feature of LeetCode?


  • 0
    S

    The following code (C++) gets a compile error from LeetCode:

    class Solution {
    private:
        struct majorElem {
            int elem;
            int count;
            
            majorElem (int elem) : elem (elem), count (1) {}
        };
        
    public:
        int majorityElement(vector<int>& nums) {
            
            majorElem major (nums [0]);
            
            for (int idx = 1; idx < nums.size (); ++idx) {
                if (major.count == 0) {
                    major = majorElem (nums [idx]);
                    continue;
                }
                
                major.count += nums [idx] == major.elem ? 1 : -1;
            }
            
            return major.elem;
        }
    };
    

    The error says "Line 16: major is not defined in this scope".

    Line 16 is "if (major.count == 0)"

    But the code compiles and runs fine on my Ubuntu laptop with g++ 4.8.4.

    However, if I change the variable name from "major" to something else, say "majority", it then compiles perfectly fine. Which is weird.


Log in to reply
 

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