LeetCode August check-in day1 632. Minimum interval (application of multimap-repetitive storage of key values)

Topic link

Insert picture description here

Ideas:

  • Use multimap to store each element in the two-dimensional vector in the form of (element value, group). Since the element value may be repeated, the multmap is used to store it here.
  • Use the sliding window to linearly traverse the stored elements in the multimap from the beginning to the end, and use a map to record how many groups of elements have been traversed.
  • When it is detected that map.size() contains each group, the left end of the window is reduced, and the minimum difference between the left end and the right end is recorded during the process.
  • The final left and right values ​​are the answer
class Solution {
    
    
public:
    vector<int> smallestRange(vector<vector<int>>& nums) {
    
    
            multimap<int,int>div;
            map<int,int>temp;
            for(int i=0;i<nums.size();i++)
            {
    
    
                for(int j=0;j<nums[i].size();j++)
                {
    
    
                    div.insert(pair<int,int>(nums[i][j],i));
                }
            }
            auto left=div.begin();
            auto right=div.begin();
            int res=INT_MAX;
            int k=nums.size();
            int l=0,r=0;
            vector<int> ans;
            while(right!=div.end())
            {
    
    
                temp[right->second]++;
                while(temp.size()==k)
                {
    
    
                    if(right->first-left->first<res)
                    {
    
    
                        res=right->first-left->first;
                        l=left->first;
                        r=right->first;
                    }
                    temp[left->second]--;
                    if(temp[left->second]==0)
                    {
    
    
                        temp.erase(left->second);
                    }
                    left++;
                }
                right++;
            }
                if(res!=INT_MAX)
                {
    
    
                    ans.push_back(l);
                     ans.push_back(r);
                }
           
            return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/107747755