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.

这道题给了我们一个数组,让我们找出最长的和谐子序列,关于和谐子序列就是序列中数组的最大最小差值均为1。由于这里只是让我们求长度,并不需要返回具体的子序列。所以我们可以对数组进行排序,那么实际上我们只要找出来相差为1的两个数的总共出现个数就是一个和谐子序列的长度了。明白了这一点,我们就可以建立一个数字和其出现次数之间的映射,利用 TreeMap 的自动排序的特性,那么我们遍历 TreeMap 的时候就是从小往大开始遍历,我们从第二个映射对开始遍历,每次跟其前面的映射对比较,如果二者的数字刚好差1,那么就把二个数字的出现的次数相加并更新结果 res 即可,参见代码如下:

解法一:

class Solution {
public:
int findLHS(vector<int>& nums) {
if (nums.empty()) return ;
int res = ;
map<int, int> m;
for (int num : nums) ++m[num];
for (auto it = next(m.begin()); it != m.end(); ++it) {
auto pre = prev(it);
if (it->first == pre->first + ) {
res = max(res, it->second + pre->second);
}
}
return res;
}
};

其实我们并不用向上面那种解法那样用 next 和 prev 来移动迭代器,因为其用到了 TreeMap 的自动排序功能,所以才可以利用 next 和 prev。其实我们还可以用 HashMap 来做,先遍历一遍,建立每个数字跟其出现次数之间的映射,然后再遍历每个数字的时候,只需在 HashMap 中查找该数字加1是否存在,存在就更新结果 res,这样更简单一些,参见代码如下:

解法二:

class Solution {
public:
int findLHS(vector<int>& nums) {
int res = ;
unordered_map<int, int> m;
for (int num : nums) ++m[num];
for (auto a : m) {
if (m.count(a.first + )) {
res = max(res, m[a.first] + m[a.first + ]);
}
}
return res;
}
};

我们其实也可以在一个 for 循环中搞定,遍历每个数字时,先累加其映射值,然后查找该数字加1是否存在,存在的话用 m[num] 和 m[num+1] 的和来更新结果 res,同时,还要查找该数字减1是否存在,存在的话用 m[num] 和 m[num-1] 的和来更新结果 res,这样也是可以的,参见代码如下:

解法三:

class Solution {
public:
int findLHS(vector<int>& nums) {
int res = ;
unordered_map<int, int> m;
for (int num : nums) {
++m[num];
if (m.count(num + )) {
res = max(res, m[num] + m[num + ]);
}
if (m.count(num - )) {
res = max(res, m[num] + m[num - ]);
}
}
return res;
}
};

下面方法不用任何 map,但是需要对数组进行排序,当数组有序了之后,我们就可以一次遍历搞定了。这实际上用到了滑动窗口 Sliding Window 的思想,用变量 start 记录当前窗口的左边界,初始化为0。用 new_start 指向下一个潜在窗口的左边界,初始化为0。i为当前窗口的右边界,从1开始遍历,首先验证当前窗口的差值是否小于1,用 nums[i] 减去  nums[start],若不满足,则将 start 赋值为 new_start,即移动到下一个窗口。然后看当前数字跟之前一个数字是否相等,若不相等,说明当前数字可能是下一个潜在窗口的左边界,将 new_start 赋值为i。然后再看窗口的左右边界值是否刚好为1,因为题目中说了差值必须正好为1,由于我们对数组排序了,所以只要左右边界差值正好为1,那么这个窗口包含的数字就可以组成满足题意的子序列,用其长度来更新结果 res 即可,参见代码如下:

解法四:

class Solution {
public:
int findLHS(vector<int>& nums) {
int res = , start = , new_start = ;
sort(nums.begin(), nums.end());
for (int i = ; i < nums.size(); ++i) {
if (nums[i] - nums[start] > ) start = new_start;
if (nums[i] != nums[i - ]) new_start = i;
if (nums[i] - nums[start] == ) res = max(res, i - start + );
}
return res;
}
};

参考资料:

https://leetcode.com/problems/longest-harmonious-subsequence/

https://leetcode.com/problems/longest-harmonious-subsequence/discuss/103497/Simple-Java-HashMap-Solution

https://leetcode.com/problems/longest-harmonious-subsequence/discuss/103499/Three-C%2B%2B-Solution-run-time-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Longest Harmonious Subsequence 最长和谐子序列的更多相关文章

  1. [LeetCode] Longest Increasing Subsequence 最长递增子序列

    Given an unsorted array of integers, find the length of longest increasing subsequence. For example, ...

  2. poj 2533 Longest Ordered Subsequence 最长递增子序列

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4098562.html 题目链接:poj 2533 Longest Ordered Subse ...

  3. leetcode300. Longest Increasing Subsequence 最长递增子序列 、674. Longest Continuous Increasing Subsequence

    Longest Increasing Subsequence 最长递增子序列 子序列不是数组中连续的数. dp表达的意思是以i结尾的最长子序列,而不是前i个数字的最长子序列. 初始化是dp所有的都为1 ...

  4. lintcode 77.Longest Common Subsequence(最长公共子序列)、79. Longest Common Substring(最长公共子串)

    Longest Common Subsequence最长公共子序列: 每个dp位置表示的是第i.j个字母的最长公共子序列 class Solution { public: int findLength ...

  5. C#LeetCode刷题之#594-最长和谐子序列​​​​​​​​​​​​​​(Longest Harmonious Subsequence)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3800 访问. 和谐数组是指一个数组里元素的最大值和最小值之间的差 ...

  6. LeetCode Longest Harmonious Subsequence

    原题链接在这里:https://leetcode.com/problems/longest-harmonious-subsequence/description/ 题目: We define a ha ...

  7. [LeetCode] Longest Palindromic Subsequence 最长回文子序列

    Given a string s, find the longest palindromic subsequence's length in s. You may assume that the ma ...

  8. LeetCode 300. Longest Increasing Subsequence最长上升子序列 (C++/Java)

    题目: Given an unsorted array of integers, find the length of longest increasing subsequence. Example: ...

  9. [LeetCode] 300. Longest Increasing Subsequence 最长递增子序列

    Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Inp ...

随机推荐

  1. js网页判断移动终端浏览器版本信息是安卓还是苹果ios,判断在微信浏览器跳转不同页面,生成二维码

    一个二维码,扫描进入网页,自动识别下载苹果和安卓客户端,判断网页如下,(只有苹果的微信不能自动跳转)所以加个微信判断. <!DOCTYPE html> <html> <h ...

  2. React demo:express、react-redux、react-router、react-roter-redux、redux-thunk(一)

    近期终于把之前留下的坑填上了(说了好久的要网站重写,总算是写完了),不过最后的在线添加文章,功能虽然做了,后台没把接口加上,实在是没精力去折腾了,公司又有事要忙,现在把从0开始到完成的一个思路来写一下 ...

  3. 用Python满足满足自己的“小虚荣”

    首先声明,学习这个只是为了好玩,只是为了好玩,并不是想用这个弄虚作假,做一些不好的事情!一心想做技术人,自制自治! 我们有时候发布一篇日志,或者是一篇博文,总希望自己的浏览量能高点,这样看起来也倍有面 ...

  4. 201621123050 《Java程序设计》第2周学习总结

    1.本周学习总结 java的数据类型 基本数据类型:介绍了java特有的boolean 引用数据类型 String:不变性:需要频繁修改时使用StringBuilder 包装类:自动拆.装箱 数组 一 ...

  5. 展示博客(Beta版本)

    团队:xjbz 1. 团队成员博客,源码仓库地址. coding:https://git.coding.net/z404395979/xjbz.git 钟平辉(071):http://www.cnbl ...

  6. jsonp处理

    def loads_jsonp(self,_jsonp): try: return json.loads(re.match(".*?({.*}).*",_jsonp,re.S).g ...

  7. io多路复用(三)

    #!/usr/bin/env python # -*- coding:utf-8 -*- import socket sk1 = socket.socket() sk1.bind(('127.0.0. ...

  8. 同一个页面同时拥有collectionView和navigationBar和tabBar时可能遇到的问题

    写一个页面的时候,遇到了页面加载时候collectionView的最下面少了49个像素的位置,切换去别的页面之后,再返回,又变回正常,多方求解无果后,发现原来是系统自带的适应功能导致的,加入以下代码即 ...

  9. recompose mapProps

    mapProps介绍 mapProps函数接收一个函数参数,这个函数参数会返回一个对象用作为接下来的组件的props.组件接收到的props只能是通过mapProps函数参数返回的对象,其他的prop ...

  10. 吝啬的国度 nyoj

    吝啬的国度 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 在一个吝啬的国度里有N个城市,这N个城市间只有N-1条路把这个N个城市连接起来.现在,Tom在第S号城市, ...