求最长连续子序列的长度

给你一个排序的数组,例如 { 1, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15 } ,求最长连续子序列的长度

public static int getLongest(int[] strs) {
    int max = 0;
    int oldmax = 0;
    for (int i = 1; i < strs.length; ++i) {
        if (strs[i] - strs[i - 1] == 1) {
            max = max + 1;
            oldmax = max;
        } else {
            max = 0;
        }
    }
    return Math.max(max, oldmax);
}

时间复杂度应该是 O(n)

如果变形呢?给你一个没有排序的。

  1. 先对数组进行排序,然后再进行如上操作
  2. 结合 hash 表
public static int getLongestV2(int[] strs) {
    Map<Integer, Integer> map = new HashMap<>();
    int max = 0;
    for (int str : strs) {
        // 0 表示没有处理过
        if (map.getOrDefault(str, 0) == 0) {
            int left = map.getOrDefault(str - 1, 0); // 左序列长度
            int right = map.getOrDefault(str + 1, 0); // 右序列长度
            map.put(str, right + left + 1);
            // 设置左端点
            if (left != 0) {
                map.put(str - left, left + right + 1);
            }
            // 设置右端点
            if (right != 0) {
                map.put(str + right, right + left + 1);
            }
            max = max > (left + right + 1) ? max : (left + right + 1);
        }
    }
    return max;
}

注意:在更新两端节点的序列长度时,也要更新当前节点的序列长度。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值