Longest Harmonious Subsequence(C++最长和谐子序列)

解题思路:

(1)根据map的依据key排序属性,将数组中的数字从大到小排序

(2)接下来遍历map,判断相邻key是否相差1,同时更新它们的value之和

class Solution {
public:
    int findLHS(vector& nums) {
        if(nums.size()==0 || nums.size()==1) return 0;
        map mp;
        int len = 0;
        for(auto&w : nums) mp[w]++;
        
        map::iterator cur = mp.begin();
        map::iterator nex = next(cur);
        
        while(nex!=mp.end()) {
            if(cur->first+1==nex->first)
                len = (cur->second+nex->second)>len?(cur->second+nex->second):len;
            cur = nex;
            nex++;
        }
        return len;
    }
};

 

你可能感兴趣的:(LintCode,C++,LeetCode)