1. 程式人生 > >594. Longest Harmonious Subsequence(python+cpp)

594. Longest Harmonious Subsequence(python+cpp)

題目:

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.

解釋: 由於是subsequence,所以可以隨便抽選,找到合起來個數最多的兩個數字即可,subsequence的長度就是這兩個數字個數的總和。 python程式碼:

import collections
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count =
collections.Counter(nums) max_len=0 for x in count: if x+1 in count: max_len=max(max_len,count[x]+count[x+1]) return max_len
#include <map>
using namespace std;
class Solution {
public:
    int findLHS(vector<int>& nums) {
        map<
int ,int >_map; for (auto num:nums) _map[num]++; int max_len=0; for(auto& item:_map) { if(_map.count(item.first+1)) max_len=max(max_len,_map[item.first]+_map[item.first+1]); } return max_len; } };

總結: 合理使用字典,恩