Longest_consecutive_sequence

package com.ytx.array;
import java.util.HashSet;
import java.util.Set;
/**
 *     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)。
   
    思路:最开始想到先排序,但是要求算法复杂度为O(n),又有可能有负数,还是不行,
    但是牛客网上很多提交排在前面的都是用内部排序比如,C++的sort函数,但是底层实现不也是快排优化而来吗,最快也是O(nlogn),为什么能通过。
  底下解法的思路,是利用容器Set,先把数组中的所有数装进容器Set中,然后开始遍历,在容器中找到这个数x,就把它去除,pre为x的前一个数,
  next为x的后一个数,分别向前和向后找,只要在Set中能找到并去除,pre--,next就++,然后next-pre-1就是得到了这次循环找到的最大连续
  序列的长度,因为我们需要找到所有循环中的最大值,所以用Math.max()函数比较,此次循环和前一次的max_length中的较大值。
 * @author yuantian xin
 *
 */
public class Longest_consecutive_sequence {
       public static int longestConsecutive(int[] num) {
             if(num == null || num.length < 0)
                    return 0;
             Set<Integer> set = new HashSet<Integer> ();
             for(int i = 0; i < num.length; i++) {
                    set.add(num[i]);
             }
             int pre,next;
             int max_length = 0;
             for(int i = 0; i < num.length; i++) {
                    if( set.size() <= 0) break;
                    if(set.remove(num[i])) {
                           //前一个数
                           pre = num[i] - 1;
                           //后一个数
                           next = num[i] + 1;
                           //向前找,找到就从容器中移除
                           while(set.remove(pre)) --pre;
                           //向后找,找到就从容器中移除
                           while(set.remove(next)) ++next;
                           max_length = Math.max(max_length, next - pre -1);
                    }
             }
             
        return max_length;
    }
       public static void main(String[] args) {
             int num[] = {100, 4, 200, 1, 3, 2};
             System.out.println(longestConsecutive(num));
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值