• 594. Longest Harmonious Subsequence


    We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

    Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

    Example 1:

    Input: [1,3,2,2,5,2,3,7]
    Output: 5
    Explanation: The longest harmonious subsequence is [3,2,2,2,3].
    

    Note: The length of the input array will not exceed 20,000.

    Solution: line12, to access the pair in map,p.first & p.second represent the key and value in the pair. use map[key] to access the corresponding value

     1 class Solution {
     2 public:
     3     int findLHS(vector<int>& nums) {
     4         if (!nums.size()) return 0;
     5         int res=0;
     6         map<int,int> m;
     7         for (int num:nums){
     8             m[num]++;
     9         }
    10         int lastNum=0;
    11         int lastFreq=0;
    12         for (pair<int,int> p:m){
    13             int length=0;
    14             if (lastFreq && p.first-lastNum==1){
    15                 length=p.second+lastFreq;
    16             }
    17             res=max(res,length);
    18             lastNum=p.first;
    19             lastFreq=p.second;
    20         }
    21         return res;
    22     }
    23 };
  • 相关阅读:
    ELK 一些截图
    AD域
    NPOI
    搭建harbor
    【【【【日常问题记录】】】】
    golang yaml配置文件解析
    golang操作mysql使用总结
    【转】mysql优化步骤
    【转】Mysql事务,并发问题,锁机制
    golang curl
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6886135.html
Copyright © 2020-2023  润新知