LeetCode - longest-consecutive-sequence

题目:

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.

 

大概意思:

求最长连续序列

要求 复杂度为O(n)

解题思路:

要求复杂度为0(n)这里可以使用哈希表 可以用HashMap 或者HashSet集合来解决

通过HashSet来将数组元素全部添加进来,然后遍历原数组,如果某数字在HashSet里面存在,那么将他删除,同时设置当前值的前后指针,通过删除前后指针来判断这个值的连续序列是多少,那么当前值的最大序列就是 前指针-后指针-1; 那为什么要删除这个值呢,因为如果遍历1的时候,那么同时也遍历了 2,3,4 ,那么当下一次遍历2的时候,又需要遍历1,3,4 这里面也浪费了大量时间

 

下面是代码:

	public int longestConsecutive(int[] num) {
		
		if(num == null || num.length ==0) {
			return 0;
		}
		
		HashSet<Integer> set = new HashSet<Integer>();
		
		int result = 0;
		
		for(int i : num) {
			set.add(i);
		}
		
		for(int i :num) {
			while(set.remove(i)) {
				int pre = i+1;
				int rear = i-1;
				while(set.remove(pre)) {
					pre++;
				}
				while(set.remove(rear)) {
					rear--;
				}
				result = Math.max(result, pre-rear-1);
			}
		}
		
		return result;
        
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值