Skip to content

Commit 2b7ce14

Browse files
longest consecutive sequence using HashSet
1 parent 8f6b16b commit 2b7ce14

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

HARD/src/hard/LongestConsecutiveSequence.java

+28
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,32 @@ public int maxUnion(){//this is O(n)
5858
return max;
5959
}
6060
}
61+
62+
class Solution_using_HashSet{
63+
//inspired by this solution: https://discuss.leetcode.com/topic/25493/simple-fast-java-solution-using-set
64+
public int longestConsecutive(int[] nums) {
65+
if(nums == null || nums.length == 0) return 0;
66+
67+
Set<Integer> set = new HashSet();
68+
for(int i : nums) set.add(i);
69+
int max = 1;
70+
71+
for(int num : nums){
72+
if(set.remove(num)){
73+
int val = num;
74+
int count = 1;
75+
while(set.remove(val-1)) val--;//we find all numbers that are smaller than num and remove them from the set
76+
count += num - val;
77+
78+
val = num;
79+
while(set.remove(val+1)) val++;//then we find all numbers that are bigger than num and also remove them from the set
80+
count += val - num;
81+
82+
max = Math.max(max, count);
83+
}
84+
}
85+
return max;
86+
}
87+
88+
}
6189
}

0 commit comments

Comments
 (0)