Facts about map/unordered_map

Правка en2, от I_m_sfg, 2023-08-25 23:47:26

Hi, this side Imsfg. I used both map/unordered_map since long time. I observed some facts about about this special stl.

1- According to me use mp[i]==0 instead of mp.find(i) because let suppose you increase the value of mp[i]++.after that you decrease the same value mp[i]--. after u find mp.find(i). it show true but according to you this give 0 and does not exist in map. if you not understand what i am saying please see both code u can observed what i say. Case 1-use mp[i]==0 int longestKSubstr(string s, int k) {

int i=0,j=0;

    int cnt=0;

    int ans=-1;

    map<char,int>mp;

    while(i<s.size()){

        while(cnt>k and j<=i){

            mp[s[j]]--;

            if(mp[s[j]]==0){

                cnt--;

            }
            j++;

        }
        if(mp[s[i]]==0){

            cnt++;

        }
        if(cnt==k){

            ans=max(ans,i-j+1);

        }
        mp[s[i]]++;

        i++;

    }


    return ans;
}

Case 2- use mp.find(i)

    //User function template for C++

class Solution{

public:

int longestKSubstr(string s, int k) {


    int i=0,j=0;

    int cnt=0;

    int ans=-1;

    map<char,int>mp;

    while(i<s.size()){

        while(cnt>k and j<=i){

            mp[s[j]]--;

            if(mp[s[j]]==0){

                cnt--;

            }

            j++;

        }
        if(mp.find(s[i])==mp.end()){

            cnt++;

        }

        if(cnt==k){

            ans=max(ans,i-j+1);

        }

        mp[s[i]]++;

        i++;

    }

    return ans;

}

};

hopefully You understand what I am saying.....

Теги c++, hashmap, unordered_map

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский I_m_sfg 2023-08-25 23:47:26 96
en1 Английский I_m_sfg 2023-08-25 23:45:23 1898 Initial revision (published)