C ++中最长的和谐子序列
因此,如果输入类似于[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