LeetCode 594. Longest Harmonious Subsequence

来源:互联网 发布:南阳seo哪家专业 编辑:程序博客网 时间:2024/06/03 19:17

594. Longest Harmonious Subsequence

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: 5Explanation: The longest harmonious subsequence is [3,2,2,2,3].Note: The length of the input array will not exceed 20,000

Solution

  • 题意即给定一个数组,在其中找到找到一个最长数列,该数列保证只有两种数且两数之差为1。
  • 我的做法就是将nums中的数通过map映射到一个较小的方便遍历的数,然后通过hnum保存这些数的个数,findvalue实现通过key查找value,在遍历的时候,根据差值为1来更新rnt。代码如下,代码比语言更好理解……
  • 由于我对c++不是很熟悉,vector、map用得十分凌乱,代码可能多处冗余,请不吝指教。
class Solution {public:    int findLHS(vector<int>& nums) {        int hnum[20010] = {0},MIN = 100000,MAX = -100000,index = 0,rnt = 0;        map<int,int> m;        int findvalue[20010];        sort(nums.begin(),nums.end());        for (int i = 0;i < nums.size();i++) {            if (m.count(nums[i]) > 0) {                hnum[m[nums[i]]]++;            }            else {                m[nums[i]] = index++;                hnum[index - 1] = 1;                findvalue[index - 1] = nums[i];             }        }        for (int i = 1;i < index;i++) {            if (findvalue[i] - findvalue[i - 1] == 1) rnt = max(rnt,hnum[i - 1] + hnum[i]);        }        return rnt;    }};