Longest Consecutive Sequence:無序數列中查詢最長連續子串長度
阿新 • • 發佈:2019-01-23
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
思路:如果不對複雜度有要求,可以考慮排序。然而此題不允許超過O(N)複雜度,所以要空間換時間。
因為題中是查詢連續元素,所以快速的查詢考慮雜湊,而且連續元素之間值相差為1,所以據此可以在hashset中逐個元素搜尋,找到最大連續子串長度。
class Solution { public int longestConsecutive(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i :nums){ set.add(i); } int ans = 0; for(int i : set){ if(set.contains(i-1)) continue; int now = i; int sum = 1; while(set.contains(now+1)){ now++; sum++; } ans = Math.max(ans,sum); } return ans; } }