# (Easy) 594. Longest Harmonious Subsequence ## Run Code ![](https://i.imgur.com/M28Vioz.png) ## 題意 出array中相差為1,且兩者相加為最多的。 ## 解題思路 先記錄nums中相同的數字分別有幾個,最後再找分別相差為1的相加是否為最大值。 ## 困難之處 Nope ## Code ```cpp= class Solution { public: int findLHS(vector<int>& nums) { //所以要找出array中相差為1,且最多的。 //因此用map啦 map<int, int> hashmap; int answer = 0; for(auto i:nums) //i 是iterator of nums(vector),偷懶的寫法www hashmap[i]++; map<int, int>::iterator it1 = hashmap.begin(), it2 = ++hashmap.begin(); for(;it2!=hashmap.end();it2++,it1++) //first is key, second is value if(it1->first + 1 == it2->first) answer = max(answer, it1->second + it2->second); return answer; } }; ``` ###### tags: `leetcode`