NC95 数组中的最长连续子序列

数组中的最长连续子序列

https://www.nowcoder.com/practice/eac1c953170243338f941959146ac4bf?tpId=188&&tqId=38566&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

哈希表
如果存在num-1 说明 num不是起始

找到起始 从start = num 开始搜索 知道搜索不到star+1 结束
计算最长长度
返回

import java.util.*;


public class Solution {
    /**
     * max increasing subsequence
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int MLS (int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr) set.add(num);
        int maxlen = 0;

        for(int num : arr){
            if(set.contains(num -1)) continue;
            int start = num;
            while(set.contains(start+1)) start++;
            maxlen = Math.max(maxlen,start-num+1);
        }
        return maxlen;
    }
}

也可以无序排成有序

全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务