假设我们有一个整数数组;我们必须在所有可能的子序列中找到最长的和谐子序列的长度。众所周知,和谐序列数组是其最大值和最小值之差恰好为1的数组。
因此,如果输入类似于[1,3,2,2,5,2,3,7],则输出将为5,因为最长的和谐子序列为[4,3,3,3,4]。
为了解决这个问题,我们将遵循以下步骤-
定义一张映射
对于以数字为单位的n-
(将m [n]增加1)
对于m中的键值对(k,v)-
max _:= max_的最大值及其值
它:=(k + 1)在m中的位置
如果'it'以m为单位,则-
返回max_
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findLHS(vector<int>& nums) {
      unordered_map<int, int> m;
      for (const int n : nums)
         ++m[n];
      int max_{ 0 };
      for (const auto & [ k, v ] : m) {
         auto it = m.find(k + 1);
         if (it != m.end())
            max_ = max(max_, v + it->second);
      }
      return max_;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,4,3,3,6,3,4,8};
   cout << (ob.findLHS(v));
}{2,4,3,3,6,3,4,8}输出结果
5