LeetCode Note Java 00128:Longest Consecutive Sequence

返回 int Array 中最長的連續數字長度。

題目

Longest Consecutive Sequence Medium

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

我的解法

  • 先排序。
  • 再來就數連續相差 1 的數量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int longestConsecutive(int[] nums) {
if (nums.length < 2) {
return nums.length;
}
Arrays.sort(nums);
int right = 1, cLength = 1, cMaxLength = 1;
while (right < nums.length) {
int diff = nums[right] - nums[right - 1];
if (diff == 1) {
cLength++;
}else if (diff > 1) {
cLength = 1;
}
if (cLength > cMaxLength) {
cMaxLength = cLength;
}
right++;
}
return cMaxLength;
}
}

結果意外的簡單。