Longest Consecutive Sequence
Problem:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
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.
Analysis:
- store all numbers to set
- iterate through the array, check if n - 1 exist
- n - 1 not exist, current number is the start of the sequence.
- count current sequence with set
HashMap is power full don't afraid to use it.
Solution:
class Solution { public int longestConsecutive(int[] nums) { if (nums == null || nums.length == 0) return 0; Set<Integer> numsSet = HashSet<>(); int res = 0; for (int n: nums) { numsSet.add(n); } for (int n: nums) { if (!numsSet.contains(n - 1)) { int curNum = n; int curRes = 1; while (numsSet.contains(curNum++)) { curRes++; } res = Math.max(res, curRes); } } return res; } }
评论
发表评论