File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Constraints:
3
+ * - 0 <= nums.length <= 105
4
+ * - -109 <= nums[i] <= 109
5
+ *
6
+ * Output
7
+ * - 가장 긴 길이
8
+ *
9
+ * 풀이 특이점
10
+ * - 둘다 시간복잡도는 O(N)으로 생각되는데 Runtime의 결과 차이가 꽤 크게 나온 점
11
+ */
12
+
13
+ class Solution {
14
+ public int longestConsecutive (int [] nums ) {
15
+ // (1) Set & num -1
16
+ // 시간복잡도 : O(N)
17
+ // Runtime : 1267ms Beats 5.15%
18
+ // Memory : 63.30MB Beats 62.58%
19
+ // Set<Integer> uniqueNums = Arrays.stream(nums).boxed().collect(Collectors.toSet());
20
+ // int result = 0;
21
+
22
+ // for (int num : nums) {
23
+ // if (uniqueNums.contains(num - 1)) continue;
24
+ // int length = 1;
25
+ // while (uniqueNums.contains(num + length)) length += 1;
26
+ // result = Math.max(length, result);
27
+ // }
28
+
29
+ // return result;
30
+
31
+ // (2) HashMap
32
+ // 시간복잡도 : O(N)
33
+ // Runtime : 38ms Beats 46.54%
34
+ // Memory : 66.45MB Beats 51.28%
35
+ HashMap <Integer , Boolean > hm = new HashMap <>();
36
+
37
+ for (int i =0 ; i <nums .length ; i ++){
38
+ hm .put (nums [i ], false );
39
+ }
40
+
41
+ for (int key : hm .keySet ()){
42
+ if (hm .containsKey (key - 1 )== false ){
43
+ hm .put (key , true );
44
+ }
45
+ }
46
+
47
+ int max = 0 ;
48
+ for (int key : hm .keySet ()){
49
+ int k =1 ;
50
+ if (hm .get (key ) == true ){
51
+ while (hm .containsKey (key + k ) == true ){
52
+ k ++;
53
+ }
54
+ }
55
+
56
+ max = Math .max (max , k );
57
+ }
58
+
59
+ return max ;
60
+ }
61
+ }
You can’t perform that action at this time.
0 commit comments