leetcode_Longest Consecutive Sequence

来源:互联网 发布:mastercam如何编程 编辑:程序博客网 时间:2024/05/22 17:03
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.


使用treeset实现,经试验发现本体要求0,0,1返回2,不是3,否则可以用treemap


package longest_Consecutive_Sequence;import java.util.Set;import java.util.TreeSet;public class Longest_Consecutive_Sequence {public static int longConsecutiveSequence(int[] array){Set<Integer> s = new TreeSet<Integer>();if(array.length==0){return 0;}for(int x : array){s.add(x);}int pre = Integer.MAX_VALUE;int cons = 1;int max = 1;for(int x : s){if(x - pre == 1){cons = cons + 1;if(cons > max){max = cons;}}else{cons = 1;}pre = x;}System.out.println(max);return max;}public static void main(String[] args) {int[] a = {9,1,4,7,3,-1,0,5,8,-1,6};longConsecutiveSequence(a);}}


原创粉丝点击