File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /* *
4
+ * HashSet을 사용한 풀이.
5
+ * 시간 복잡도 O(n)
6
+ * -> Loop를 두 번 돌기 때문에 O(n^2)이라고 생각할 수 있으나 최악의 상황이여도 O(n + (n-1))로 O(n)이 됨.
7
+ * -> 1 부터 10억까지의 연속된 수가 Set 자료구조에 담겨 있고 최악의 상황으로 1이 마지막 순번에 뽑힌다고 가정했을 때, (Set은 순서가 존재하지 않음)
8
+ * -> 1 부터 Longest Count 하더라도 주어진 nums에서 n 번 set에서 10억 -1번을 순회하므로 O(n^2)이 아닌 O(n)이 됨.
9
+ */
10
+ fun longestConsecutive (nums : IntArray ): Int {
11
+ val numSet: HashSet <Int > = nums.toHashSet()
12
+ var longest = 0
13
+
14
+ for (num in nums) {
15
+ // 현재 요소보다 크기가 1 작은 숫자를 갖고 있다면 현재 요소는 최소값이 아니므로 다음으로 넘어감
16
+ if (numSet.contains(num - 1 )) {
17
+ continue
18
+ }
19
+ // 현재 요소보다 1 작은 연속된 숫자가 없으므로 현재 원소를 1 카운트 한 length 할당
20
+ var length = 1
21
+ while (numSet.contains(num + length)) {
22
+ length++
23
+ }
24
+ longest = max(longest, length)
25
+ }
26
+ return longest
27
+ }
28
+
29
+ /* *
30
+ * Time Limit 발생.
31
+ * 시간 복잡도 O(n^2)
32
+ * -> nums 안에 존재하는 요소마다 중복을 포함한 Loop(while) 진행
33
+ */
34
+ fun longestConsecutive01 (nums : IntArray ): Int {
35
+ // 결과를 담을 리스트
36
+ val resultList = mutableListOf<Int >()
37
+
38
+ // 1차 loop
39
+ for (i in nums.indices) {
40
+ var tempResult = 0
41
+ var currentNum = nums[i]
42
+ // 2차 loop
43
+ while (true ) {
44
+ if (nums.contains(currentNum)) {
45
+ tempResult + = 1
46
+ currentNum + = 1
47
+ } else {
48
+ break
49
+ }
50
+ }
51
+ resultList.add(tempResult)
52
+ }
53
+ if (resultList.isEmpty()) {
54
+ return 0
55
+ }
56
+ return resultList.max()
57
+ }
You can’t perform that action at this time.
0 commit comments