Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2b7ce14

Browse files
longest consecutive sequence using HashSet
1 parent8f6b16b commit2b7ce14

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎HARD/src/hard/LongestConsecutiveSequence.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,32 @@ public int maxUnion(){//this is O(n)
5858
returnmax;
5959
}
6060
}
61+
62+
classSolution_using_HashSet{
63+
//inspired by this solution: https://discuss.leetcode.com/topic/25493/simple-fast-java-solution-using-set
64+
publicintlongestConsecutive(int[]nums) {
65+
if(nums ==null ||nums.length ==0)return0;
66+
67+
Set<Integer>set =newHashSet();
68+
for(inti :nums)set.add(i);
69+
intmax =1;
70+
71+
for(intnum :nums){
72+
if(set.remove(num)){
73+
intval =num;
74+
intcount =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+
returnmax;
86+
}
87+
88+
}
6189
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp