128. Longest Consecutive Sequence

Longest Consecutive Sequence

题目

给出一个无序整数数组,找出最长连续序列的长度。

比如:
给出数组[100, 4, 200, 1, 3, 2],
最长连续序列是[1, 2, 3, 4]. 返回它的最大长度:4.

你的算法复杂度为O(n)。

代码块

class Solution {
    public static int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>();
        if(nums.length == 0)return 0; //数组长度为
        for(int i : nums){
            hs.put(i,0);//将数组元素放进hashmap
        }
        int maxl = 1;//将最大长度赋为1
        for(int i : nums){
            if(hs.get(i)==1)
                continue;

            int temp = i ;
            int current_max = 1;//当前最大长度
            while(hs.containsKey(temp+1)){  //找有没有比key值大的连续数
                current_max ++;
                temp ++;
                hs.put(temp,1);
            }

            temp = i ;//再将key给临时值

            while(hs.containsKey(temp-1)){  //找有没有比key值小的连续数
                current_max ++;
                temp --;
                hs.put(temp,1);
            }

            maxl =Math.max(maxl, current_max); //找出最大长度
        }

        return maxl;

    }
     public static void main(String[] args) {
        int[] nums = {100,4,200,1,2,3};
        System.out.println(longestConsecutive(nums));
    }
}

代码分析

本题对算法复杂度进行了要求,所以不能使用排序,需要使用HashMap。
通过关键值来访问value,算法复杂度为O(n).

keyvalue
0a
1b
2c

hm.get(0)=a

第一步:建立一个HashMap;
第二步:将数组的元素放进HashMap,同时将value值置为0;i为key值,然后将key赋给一个临时值,分别向上向下找连续值,有的话,就将value置为1,并将此作为是否再找的条件。
比如4,向上没有5,向下找到了(3,2,1)这些值的value为1,下次遇到就不再循环。
第三步:返回最大长度。

Math.max是找最大值的函数,也可以直接引用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值