LeetCode @ Longest Consecutive Sequence 求最长连续整数串 D4F3

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

思路来自Code_ganker:http://blog.csdn.net/linhuanmars/article/details/22964467

注意:关于时间复杂度的解释,双层loop是O(n*n),但是不同层的2个loop是O(2*n)=O(n)。

以及Souldak:http://blog.csdn.net/souldak/article/details/11473425

注意:对于HashSet和HashMap的理解!

<span style="font-size:14px;">public class Solution {
    public int longestConsecutive(int[] num) {
        if(num.length==0 || num==null)
            return 0;
        int res=1;
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i=0; i<num.length; i++){//遍历Array,把元素放入HashSet
            set.add(num[i]);
        }       
        while(!set.isEmpty()){
            Iterator<Integer> it = set.iterator();
            int item = it.next();    //迭代器获取当前元素并删之
            set.remove(item);        //【注意1】
            int len=1;
            int i=item-1;      //比当前值小1的连续Integer
            while(set.contains(i)){
                set.remove(i--);
                len++;
            }
            i=item+1;          //比当前值大1的连续Integer
            while(set.contains(i)){
                set.remove(i++);
                len++;
            }
            if(len>res)
                res=len;
        }
        return res;//Math.max(res,len),compile Error【注意3】
    }
}</span>

【注意1】没写remove,OJ时候[0,0]的TestCase超时了。在JDK上run过,num=[0,0]的结果是1。
【注意2】此处的return表达式不可以含len,因为len在while内定义,只限于循环内部使用!
【注意3】HashSet和Iterator要import java.util.*;HashSet不可以存相同值,否则第二次set.add(sameItem),会返回false。


【后记】用HashMap的做法,来源于“【LV3】霸yx”

<span style="font-size:14px;">public class Solution {
    public int longestConsecutive(int[] num) {
        if(num.length==0 || num==null)
            return 0;
        int maxl=1;
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int item:num)
            map.put(item,0);
        for(int i:num){
            if(map.get(i)==1)
                continue;
            int temp=i;
            int currentMax=1;
            while(map.containsKey(temp+1)){
                currentMax++;
                temp++;
                map.put(temp,1);
            }
            temp=i;
            while(map.containsKey(temp-1)){
                currentMax++;
                temp--;
                map.put(temp,1);
            }
            maxl=Math.max(maxl,currentMax);
        }
        return maxl;
    }
}</span>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值