594. Longest Harmonious Subsequence

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
找出最长的序列,要求是最大值和最小值相差不超过1.

2,题目思路
基于遍历的方法,对目前满足条件的序列记录其开始位置,并记录开始不满足条件时的位置。在开始对序列进行排序,便可以很方便的记录位置信息。
另外一种解法,则是利用map结构,对每个数字出现的次数进行统计,然后对得到的map进行遍历,看对应数字少1的数字是否出现,如果出现就统计出现次数。

3,程序源码

class Solution {
public:
    int findLHS(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0;
        for (int i = 1, start = 0, new_start = 0; i < nums.size(); i++)
        {
            if(nums[i] - nums[start] > 1)
                start = new_start;
            if(nums[i] != nums[i-1])
                new_start = i;
            if(nums[i] - nums[start] == 1)
                res = max(res,i-start+1);
        }
        return res;
    }
};

另外一种解法:

class Solution {
public:
    int findLHS(vector<int>& nums) {
        unordered_map<int ,int> m;
        for(auto num:nums)
            m[num]++;   //记录每个数字出现的次数

        int res = 0;
        for(auto it:m)
        {
            if(m.count(it.first-1)>0)
            {
                res = max(res, it.second+m[it.first-1]);
            }
        }
        return res;

    }
};

在第二种方法中,用到的是unordered_map容器,与前面讲的unordered_set类似,基础用法与set是类似的,但是其中是无序的,优点是在在进行搜索时,速度较快。
对于unordered_map,其迭代器是一个指针,指向这个元素,通过迭代器来取得它的值

unordered_map<Key,T>::iterator it;
(*it).first;             // the key value (of type Key)
(*it).second;            // the mapped value (of type T)
(*it);                   // the "element value" (of type pair<const Key,T>) 

它的键值分别是迭代器的first和second属性。

it->first;               // same as (*it).first   (the key value)
it->second;              // same as (*it).second  (the mapped value) 

unordered_map的详细介绍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值