Why this version get accepted? anyone help?


  • 0
    L
    The following version get accept, but I find a bug my self, it is weird why it is accepted?? 
    before I erase the candidate,  if (--it->second = 0) it = cand.erase(it); there should be "==", instead of "="
    
    vector<int> majorityElement(vector<int>& nums) {
        return kMajor(nums, 3);
    }
    vector<int> kMajor(vector<int> &nums, int k) {
        vector<int> res;
        unordered_map<int, int> cand;
        for (auto num : nums) {
            cand[num]++;
            if (cand.size() == 3) {
                for (auto it = cand.begin(); it != cand.end();) {
                    if (--it->second = 0) it = cand.erase(it); // here is a bug, I assign 0 to the second.
                    else it++;
                }
            }
        }
        for (auto &item : cand) item.second = 0;
        for (auto num : nums) {
            if (cand.count(num) == 1) cand[num]++;
        }
        int times = nums.size() / k;
        for (auto item : cand) {
            if (item.second > times) res.push_back(item.first);
        }
        return res;
    }

  • 0
    L

    hi, there may be a bug on the leetcode.
    ====== here is my solution ,as yours. but there is a runtime error

    vector<int> majorityElement(vector<int>& nums) {
            int n = nums.size();
            unordered_map<int,int> candTimes;
            vector<int> re;
            for(int i = 0;i<n;i++){
               if(candTimes.find(nums[i])!=candTimes.end()){
                    candTimes[nums[i]]++;
               }else{
                    if(candTimes.size()<3){
                        candTimes[nums[i]]++;
                    }else if(candTimes.size()==3){
                        for(unordered_map<int,int>::iterator mit = candTimes.begin();
                            mit!=candTimes.end();mit++){
                            if(mit->second==1){
                                candTimes.erase(mit);
                            }else{
                                mit->second--;
                            }
                        }
                    }
               }///if-else
            }///for
    
            ///verify the solution
            for(unordered_map<int,int>::iterator mit = candTimes.begin();
                mit!=candTimes.end();mit++){
                mit->second = 0;
            }
    
            for(int i = 0;i<n;i++){
                if(candTimes.find(nums[i])!=candTimes.end()){
                    candTimes[nums[i]]++;
                }
            }
    
    
            for(unordered_map<int,int>::iterator mit = candTimes.begin();
                mit!=candTimes.end();mit++){
                if(mit->second>(n/3)){
                    re.push_back(mit->first);
                }
            }
            return re;
        }

Log in to reply
 

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