LeetCode-594. Longest Harmonious Subsequence [C++][Java]

LeetCode-594. Longest Harmonious Subsequencehttps://leetcode.com/problems/longest-harmonious-subsequence/

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

Example 1:

Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Example 2:

Input: nums = [1,2,3,4]
Output: 2

Example 3:

Input: nums = [1,1,1,1]
Output: 0

Constraints:

  • 1 <= nums.length <= 2 * 10^4
  • -10^9 <= nums[i] <= 10^9

【C++】

1. sort

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

2. map

class Solution {
public:
    int findLHS(vector<int>& nums) {
        map<int, int> countForNum;
        for (int num : nums) {
            if(countForNum.find(num) == countForNum.end()) countForNum[num] = 1;
            else countForNum[num]++;
        }
        int longest = 0;
        for(map<int, int>::iterator it=countForNum.begin(); it!=countForNum.end(); ++it) {
            int num = it->first;
            if(countForNum.find(num+1) != countForNum.end()) {
                longest = max(longest, countForNum[num+1] + countForNum[num]);
            }
        }
        return longest;
    }
};

【Java】

class Solution {
    public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int res = 0 , start = 0, newstart = 0;
        for (int i=1; i<nums.length; ++i) {
            if (nums[i]-nums[start] > 1) start = newstart;
            if (nums[i] != nums[i-1]) newstart = i;
            if (nums[i]-nums[start] == 1) res = Math.max(res, i-start+1);
        }
        return res;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值