zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    原型模式
    浅复制和深复制
    适配器模式
    外观模式
    模板方法
    建造者模式
    代理模式
    Centos7重新安装yum
    关于mongodb创建索引的一些经验总结(转)
    MongoDB查询语句(转)
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6886135.html
Copyright © 2011-2022 走看看