
1. 题面
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
1 2 3
|
输入: [100, 4, 200, 1, 3, 2] 输出: 4 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
|
2. 解答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
class { public int longestConsecutive(int[] nums) {
if(nums.length == 0) return 0; int max = 1; Set<Integer> set = new HashSet<Integer>(); for(int i:nums) set.add(i); for(int num:set) { if(!set.contains(num-1)) { int len = 1; int currnum = num+1; while(set.contains(currnum)) { len++; currnum++; } max = Math.max(max, len); } } return max; } }
|
近期评论