当前位置: 首页 > java >正文

Leetcode594.最长和谐子序列

题目

594. 最长和谐子序列

算法标签: 滑动窗口, 哈希表

思路

先将数组进行排序, 检查两个相邻的但是不相等的数字的差值是否是 1 1 1, 如果是 1 1 1更新答案

滑动窗口代码

#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <set>using namespace std;class Solution {
public:int findLHS(vector<int>& nums) {sort(nums.begin(), nums.end());int l = 0, r = 0, n = nums.size();int ans = 0;while (r < n) {while (l <= r && nums[r] - nums[l] > 1) l++;if (nums[r] - nums[l] == 1) ans = max(ans, r - l + 1);r++;}return ans;}
};

哈希表代码

#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <map>using namespace std;class Solution {
public:int findLHS(vector<int>& nums) {map<int, int> mp;int n = nums.size();for (int val : nums) mp[val]++;int ans = 0;for (auto [val, cnt] : mp) {if (mp.count(val + 1)) {ans = max(ans, cnt + mp[val + 1]);}}return ans;}
};
http://www.xdnf.cn/news/2749.html

相关文章:

  • 小米云服务安卓版数据同步稳定性与安全性能测评
  • 安卓基础(接口interface)
  • 模板--进阶
  • 提高营销活动ROI:大数据驱动的精准决策
  • 使用 Electron 打包 Windows 可执行程序
  • Darvas Box黄金交易算法详解:基于XAU/USD的实战应用
  • 武装Burp Suite工具:APIKit插件_接口安全扫描.
  • 算法备案材料拟公示内容涉及什么?如何撰写?
  • opendds的配置
  • IDEA2022.3开启热部署
  • 第16节:传统分类模型-支持向量机(SVM)在图像分类中的应用
  • sources.list.d目录
  • C++(初阶)(十三)——继承
  • 【学习笔记】机器学习(Machine Learning) | 第四章(3)| 多变量线性回归
  • new的使用
  • [4282]PHP跨境电商源码-多语言商城源码/支持代理+商家入驻+分销+等等众多功能/带详细安装
  • Object.assign 浅拷贝
  • 算法思想之哈希表
  • NVIDIA新模型DAM-3B:描述一切,图像视频局部描述新突破
  • 如何设置端口映射?内网IP映射到外网访问,附无公网ip端口映射工具方法
  • DrissionPage采集京东系列——自动化登录
  • 【数据可视化-41】15年NVDA, AAPL, MSFT, GOOGL AMZ股票数据集可视化分析
  • JS错误处理的新方案 (不使用try-catch)
  • 奥威BI+AI数据分析解决方案
  • 30分钟上架鸿蒙原生应用,即时通信IM UI组件库全面适配HarmonyOS 原
  • 前后端分离: vue3+SpringBoot+ElementPlus+Axios+MyBatisPuls
  • linux离线安装zsh
  • C++ 嵌套类 (详解 一站式讲解)
  • Docker 容器虚拟化技术和自动化部署
  • FDA会议类型总结