【LeetCode】594. Longest Harmonious Subsequence

来源:互联网 发布:wrecking ball网络歌手 编辑:程序博客网 时间:2024/06/01 09:49

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.
一开始想着先排序,后来想MAP插入后就是有序的,就不用排序了。
差值正好为1,那么在MAP中一定是两个相邻的数了。

class Solution {public:    int findLHS(vector<int>& nums) {        int len=nums.size();        if(len==0)return 0;        map<int,int> mp;        for(int i=0;i<len;i++){            mp[nums[i]]++;        }        map<int, int>::iterator iter1=mp.begin();        map<int, int>::iterator iter2=mp.begin();        iter2++;    //指向MAP的第2个数据        int ans=0;        for(;iter2!=mp.end();iter1++,iter2++){            if(iter2->first-iter1->first==1){   //因为MAP是有序的,第2个比第一个大                ans=max(ans,iter2->second+iter1->second);            }        }        return ans;    }};