差值为1的子数组的长度 Longest Harmonious Subsequence

问题:

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.

解决:

①采用hash map记录数值及其个数,找到差值为1的计算总个数,取最大的即可。耗时73ms。

public class Solution {
    public int findLHS(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int n : nums) {
            map.put(n,map.getOrDefault(n,0) + 1);
        }
        int max = 0;
        int sum = 0;
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            if(map.containsKey(entry.getKey() + 1)){
                sum = entry.getValue() + map.get(entry.getKey() + 1);
                if (max < sum) {
                    max = sum;
                }
            }
        }
        return max;
    }
}

②先对数组进行排序,使用四个指针从头到尾扫描,耗时41ms.

public class Solution {
    public static int findLHS(int[] nums) {
        int max = 0;
        Arrays.sort(nums);
        int curi = 0;//指向第一个数的第一个下标
        int curj = 0;//指向第一个数的最后一个下标
        while(curj + 1 < nums.length && nums[curj + 1] == nums[0]) curj ++;//curj初始化
        for (int nexti = curj + 1;nexti < nums.length ;nexti ++ ) {//nexti指向第二个数的第一个下标
            int nextj = nexti;//nextj指向第二个数的最后一个下标
            while(nextj + 1 < nums.length && nums[nextj + 1] == nums[nexti]) nextj ++;
            if (nums[curi] + 1 == nums[nexti]) {
                max = Math.max(max,nextj - curi + 1);
            }
            curi = nexti;
            curj = nextj;
            nexti = curj;
        }
        return max;
    }
}

转载于:https://my.oschina.net/liyurong/blog/920317

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值