当前位置:网站首页>力扣练习——64 最长和谐子序列
力扣练习——64 最长和谐子序列
2022-08-10 11:00:00 【qq_43403657】
64 最长和谐子序列
1.问题描述
和谐数组是指一个数组(长度>=2)里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
如果找不到这样的数组,则输出0。
示例 :
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
2.输入说明
首先输入整数数组的长度n,2<=n<=10000
然后输入n个整数,以空格分隔。
3.输出说明
输出最长的和谐子序列的长度
4.范例
输入
8
1 3 2 2 5 2 3 7
输出
5
5.代码
#include<iostream>
#include<map>
#include<string>
#include<unordered_map>
#include<algorithm>
#include<string.h>//memset函数
using namespace std;
int maxLen(vector<int> nums)
{
unordered_map<int, int>hash;
int ans = 0;
for (int num : nums)
hash[num]++;
for (int i=0;i<nums.size();i++)
{
if (hash[nums[i]] && hash[nums[i] + 1])//若nums[i]和nums[i]+1都存在
{
ans = max(ans, hash[nums[i]] + hash[nums[i] + 1]);
}
}
return ans;
}
int main()
{
int n,tmp;
cin >> n;
vector<int> nums;
for (int i = 0; i < n; i++)
{
cin >> tmp;
nums.push_back(tmp);
}
int res = maxLen(nums);
cout << res << endl;
return 0;
}
边栏推荐
- OSSCore 开源解决方案介绍
- 1-IMU参数解析以及选择
- Gold, nine, silver and ten job-hopping seasons: technical interview questions and answers on Alibaba, Baidu, JD.com, and Meituan
- 第3章-线性方程组(3)
- AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
- LeetCode_152_乘积最大子数组
- 第二十二章 源代码文件 REST API 参考(四)
- HCIP ---- VLAN
- 杭电多校-Loop-(不确定性贪心+线段树)
- 从源码角度分析UUID的实现原理
猜你喜欢
随机推荐
老板加薪!看我做的WPF Loading!!!
flask-restplus接口地址404问题
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
POJ 3101 Astronomy (数学)
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
Chapter 22 Source Code File REST API Reference (4)
ENVI 5.3软件安装包和安装教程
金九银十跳槽旺季:阿里、百度、京东、美团等技术面试题及答案
企业如何判断数据治理是否成功?
CodeChef STRMRG String Merging (dp)
JWT 实现登录认证 + Token 自动续期方案
从脚本到剪辑,影像大师亲授的后期制作秘籍
自媒体爆款标题怎么写?手把手教你写热门标题
HDU 1520 Anniversary party (树型dp)
Dry goods!ASSANet: Making PointNet++ faster and stronger
即时零售业态下如何实现自动做账?
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists
快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
Three-phase 380V rectified voltage
暑期总结4