当前位置:网站首页>Leetcode 2190. The number that appears most frequently in the array immediately after the key (yes, once)

Leetcode 2190. The number that appears most frequently in the array immediately after the key (yes, once)

2022-06-12 16:35:00 I'm not xiaohaiwa~~~~

 Insert picture description here
I'll give you a subscript from 0 The starting array of integers nums , I'll give you an integer at the same time key , It's in nums There have been .

Statistics stay nums The array is followed by key Different integers that appear later target Number of occurrences of . In other words ,target The number of occurrences of is i Number of :

  • 0 <= i <= n - 2
  • nums[i] == key And
  • nums[i + 1] == target .

Please return and appear most Times target . The test data guarantees the most frequent occurrence of target Is the only one. .

Example 1:

 Input :nums = [1,100,200,1,100], key = 1
 Output :100
 explain : about  target = 100 , In subscript  1  and  4  There has been  2  Time , And they all follow  key .
 There are no other integers in  key  Followed by , So we go back to  100 .

Example 2:

 Input :nums = [2,2,2,2,3], key = 2
 Output :2
 explain : about  target = 2 , In subscript  1 ,2  and  3  There has been  3  Time , And they all follow  key .
 about  target = 3 , In subscript  4  Have you ever appeared  1  Time , And follow  key .
target = 2  Yes, follow closely  key  The number that appears most frequently after , So we go back to  2 .

Tips :

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • The test data ensure that the answer is unique .

Main idea : utilize map To store
Code:

class Solution {
    
public:
    typedef pair<int, int> PAIR;  
    
    struct CmpByValue {
      
        bool operator()(const PAIR& lhs, const PAIR& rhs) {
      
            return lhs.second > rhs.second;  
        }  
    };
    int mostFrequent(vector<int>& nums, int key) {
    
        map<int,int>mymap;
        for(int i=0;i<nums.size();i++)
        {
    
            if(nums[i]==key)
            {
    
                if((i+1)<nums.size())
                {
    
                    mymap[nums[i+1]]++;
                }
            }
        }
        
        // hold map Elements in are transferred to vector in  
        vector<PAIR> vec(mymap.begin(), mymap.end());  
        
        // Yes vector Sort 
        sort(vec.begin(), vec.end(), CmpByValue());  
        
        return vec[0].first;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121629144546.html