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.
Problem Solving Ideas:
Because of the time complexity of O (n), and therefore cannot be implemented by the sort, the topic is somewhat similar to the first question of Java for Leetcode 001 The second Sum also needs to be implemented with HashMap, the specific idea is to first put Nums into the map, Then for each element of the nums, check its "sphere of influence" (the subject does not involve repeating elements), the Java implementation is as follows:
public int longestconsecutive (int[] nums) {hashmap<integer, boolean> HM = new Hashmap<integer, boolean> (); int res = 0;for (int num:nums) hm.put (num, False), for (int num:nums) {if (Hm.get (num)) continue;int width = 1;for (int j = 1; Hm.containskey (NUM-J); J + +, width++) Hm.put (Num-j, True), for (int j = 1; Hm.containskey (num + j); J + +, width++) hm.put (num + j, true); res = Math. Max (res, width);} return res;}
Java for Leetcode longest consecutive Sequence