jeudi 11 août 2022

Suitable container other than unordered map? [duplicate]

I solved Josephus problem using map by erasing every killed player from the map but every erase operation is taking logarithmic time complexity, is it possible to use unordered map or any other container here? Not used vector as then erase operation will take O(n) time instead of log(n)....

Question link https://leetcode.com/problems/find-the-winner-of-the-circular-game/

//CODE

int kill(map <int,int> &v,int k,int n){
   auto i=v.begin();

  while(v.size()-1)
  {
    for(int j=1;j<k;j++)
    { 
       if( ++i==v.end() ) i=v.begin(); //checking if player to be killed is beyond last player i.e. restarting the loop
    }       
      
    int killed=(*i).first;
           
    if(++i==v.end()) //again checking if next player after killed one is beyond last player i.e. restarting the loop
    i=v.begin();
    v.erase(killed);
  } 

return  (*v.begin()).first;
}


class Solution {
public:
    int findTheWinner(int n, int k) 
   {
    map <int,int> p;
    for(int i=1;i<=n;i++)p[i]=1;
    
    return kill(p,k,n); 
    }
};

Aucun commentaire:

Enregistrer un commentaire