594. Longest Harmonious Subsequence

来源:互联网 发布:解压缩软件32位 编辑:程序博客网 时间:2024/06/11 19:19

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: 5Explanation: The longest harmonious subsequence is [3,2,2,2,3].

stl中map的底层是由红黑树实现的,而其迭代器++的方向为键值增大的方向,所以这里利用了这一点,遍历整个map,得到最大值。



class Solution {public:    int findLHS(vector<int>& nums) {       map<int, int> mp;        for(int i = 0; i != nums.size(); ++i){            if(mp.find(nums[i]) == mp.end()){                mp.insert(make_pair(nums[i], 1));            }else{                mp[nums[i]]++;            }        }        int res = 0;        bool first = true;        int pre_val, pre_num;        for(map<int, int>::iterator it = mp.begin(); it != mp.end(); ++it){            if(first){                pre_val = it->first;                pre_num = it->second;                first = false;                continue;            }            if(it->first - pre_val == 1){                res = max(res, it->second + pre_num);            }            pre_val = it->first;            pre_num = it->second;                    }        return res;    }};