本文共 705 字,大约阅读时间需要 2 分钟。
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.
Java代码:
public class Solution { public int longestConsecutive(int[] num) { Arrays.sort(num); int len = num.length; int max = 1; int count = 1; for (int i = 0; i < len - 1; i++) { if (num[i] + 1 != num[i + 1]) { if (num[i] == num[i + 1]) continue; if (max < count) max = count; count = 1; } else { count++; } } if (max < count) { max = count; } return max; }}
转载地址:http://siuni.baihongyu.com/