leetcode-594-Longest Harmonious Subsequence

Topic description:

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.

 

Function to be done:

int findLHS(vector<int>& nums)

 

illustrate:

The difference between the maximum value and the minimum value is 1, and the values ​​in the vector are all integers, so the subarray we are looking for can only contain the maximum value and the minimum value, and no other intermediate values.

So we find how many 1s there are, and how many are 2s that differ from 1 by 1 (here we find numbers in the same direction). There are several 2, and the difference from 2 by 1 (still in the same direction) is 3, how many.

After the final statistics, we can know how many elements the longest sub-array has.

 

After traversing the vector, we can use map to store the number of values.

Then traverse the map again, count the length of each subarray according to the above method, and record the longest length.

 

code show as below:

    int findLHS(vector<int>& nums) 
    {
        unordered_map < int , int > m1;//Using unordered_map is faster
         for ( int i= 0 ;i<nums.size();i++ )//Store the number of various numbers
        {
            if(!m1.count(nums[i]))
                m1[nums[i]]=1;
            else
                m1[nums[i]]++;
        }
        int max1=0;
        for(unordered_map<int,int>::iterator iter=m1.begin();iter!=m1.end();iter++)
        {
            if (m1.count(iter->first+ 1 ))//If there is a number greater than 1
            {
                max1=max(max1,m1[iter->first+1]+iter->second);
            }
        }
        return max1;
    }

The above code is concise, measured 93ms, beats 74.88% of cpp submissions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325281014&siteId=291194637