594. 最长和谐子序列

和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。

现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

示例 1:

输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].

说明: 输入的数组长度最大不超过20,000.

 

https://leetcode-cn.com/problems/longest-harmonious-subsequence/description/

 

第一个想法,排序Arrays.sort(nums),但是怕这样速度会慢。于是想用map处理...

    public int findLHS(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            Integer count1 = map.get(num);
            //首次存入的数减去20000,以此识别
            if (count1 != null) {
                if (count1 > 20000) {
                    map.put(num, count1 - 19999);
                } else {
                    map.put(num, count1 + 1);
                }
            } else {
                map.put(num, -19999);
            }
            Integer count2 = map.get(num + 1);
            //+1后的数,首次存入加上20000
            if (count2 != null) {
                if (count2 < 0) {
                    map.put(num + 1, count2 + 20001);
                } else {
                    map.put(num + 1, count2 + 1);
                }
            } else {
                map.put(num + 1, 20001);
            }
        }
        int res = 0;
        for (int count : map.values()) {
            //count小于0的数代表不存在此数-1的值,count大于20000的值则本身不存在,所以排除
            if (count > 0 && count < 20000) {
                res = Math.max(res, count);
            }
        }
        return res;
    }

通过了测试,但是...结果发现前面速度快的都是利用先排序,还以为数组长度大点排序会很慢呢,想不到还是map更慢啊。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值