Not my favorite problem … Time complexity O(N), run time beats 86.45% java submission.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution { public int longestConsecutive(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num: nums) { set.add(num); } int max = 0; for (int num: nums) { if (set.contains(num - 1)) continue; int next = num + 1, len = 1; while (set.contains(next)) { next++; len++; } max = Math.max(len, max); } return max; } }
public int longestConsecutive(int[] num) { int res = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int n : num) { if (!map.containsKey(n)) { int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0; int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0; // sum: length of the sequence n is in int sum = left + right + 1; map.put(n, sum); // keep track of the max length res = Math.max(res, sum); // extend the length to the boundary(s) // of the sequence // will do nothing if n has no neighbors map.put(n - left, sum); map.put(n + right, sum); } else { // duplicates continue; } } return res; }
近期评论