【Leetcode】594. Longest Harmonious Subsequence (Easy)

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.

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.

翻译:我们定义一个和谐序列,要求是它的最大值和最小值的差是1.现在,给定一个整数序列,你需要找到它所有可能的子序列中的最长和谐子序列。
2.思路

首先进行排序,然后用HashMap记录各个数字出现的次数。最后再次遍历数组,当当前数字 和 当前数字+1 同时出现在hashmap的key中时,记录它们出现了次数和,和当前最大值进行比较。返回最大值。

3.算法
class Solution {
    public int findLHS(int[] nums) {
        if(nums.length==0||nums.length==1){
            return 0;
        }
        Arrays.sort(nums);
        Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                int num=map.get(nums[i])+1;
                map.put(nums[i],num);
            }else{
                map.put(nums[i],1);
            }
        }
        int max=0;
        for(int i=0;i<nums.length;i++){
            if(i>=1&&nums[i]==nums[i-1]){
                continue;
            }
            if(map.containsKey(nums[i])&&map.containsKey(nums[i]+1)){
                int temp=map.get(nums[i])+map.get(nums[i]+1);
                max=max>temp?max:temp;
            }
        }
        return max;
    }
}

4.总结

注意长度为1时,返回不是1,而是0。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值