File tree 1 file changed +28
-0
lines changed
1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -58,4 +58,32 @@ public int maxUnion(){//this is O(n)
58
58
return max ;
59
59
}
60
60
}
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
+ }
61
89
}
You can’t perform that action at this time.
0 commit comments