leetcode做题总结,题目Longest Consecutive Sequence 2013/02/13

本文介绍了一种使用HashMap和HashSet高效查找数组中连续序列的方法,实现O(n)的时间复杂度,通过遍历数组并利用数据结构快速定位序列起点。

题目是在一个数组中找最长连续队列,一般这种需要迅速找值的题目首先想到的就是HashMap,将数组里的值当成key打入map中,接下来就是找序列了,由于要求复杂度时O(n)所以每个元素只能扫一遍,我的思路是先找到每个序列的起点,只从起点开始向后找序列,如果不是起点就跳过。


public int longestConsecutive(int[] num) {
        int stor=1;
        int tmp;
        int j;
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        int amount = num.length;
        for(int i=0;i<amount;i++){
            m.put(num[i],1);
        }
        for(int i=0;i<amount;i++){
            j=num[i];
            if(m.containsKey(j)&&((i==0&&m.containsKey(j+1))||(m.containsKey(j+1)&&!m.containsKey(j-1)))){
                tmp=2;
                j=j+2;
                while(m.containsKey(j++))tmp++;
                if(tmp>stor) stor=tmp;
            }
        }
        return stor;
    }

Update 2015/08/22: 上面的做法没有必要从每个初始值开始,只需要对每个点向左右同时进行扩展求出最长序列即可,而且使用hashset即可无需使用map


public class Solution {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // write you code here
        if (num.length == 0) {
		return 0;
    	}
     
    	Set<Integer> set = new HashSet<Integer>();
    	int max = 1;
     
    	for (int e : num)
    		set.add(e);
     
    	for (int e : num) {
    		int left = e - 1;
    		int right = e + 1;
    		int count = 1;
     
    		while (set.contains(left)) {
    			count++;
    			set.remove(left);
    			left--;
    		}
     
    		while (set.contains(right)) {
    			count++;
    			set.remove(right);
    			right++;
    		}
     
    		max = Math.max(count, max);
    	}
 
	return max;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值