|
| 1 | +import java.util.HashMap; |
1 | 2 | import java.util.HashSet;
|
2 |
| -import java.util.Iterator; |
| 3 | +import java.util.Map; |
3 | 4 |
|
| 5 | +/** |
| 6 | + * time complexity : O(n) |
| 7 | + */ |
4 | 8 | public class Geegong {
|
5 | 9 |
|
6 | 10 | public int longestConsecutive(int[] nums) {
|
7 |
| - |
8 | 11 | HashSet<Integer> setOfNums = new HashSet<>();
|
9 |
| - int start = 0; |
10 |
| - int end = 0; |
| 12 | + // key : startIndex , value : length |
| 13 | + Map<Integer, Integer> lengthMap = new HashMap<>(); |
| 14 | + |
| 15 | + // sort..? 를 해야될까 싶음.. |
11 | 16 |
|
12 | 17 | // initialize
|
13 | 18 | for (int num : nums) {
|
14 | 19 | setOfNums.add(num);
|
15 |
| - start = Math.min(start, num); |
16 |
| - end = Math.max(end, num); |
17 | 20 | }
|
18 | 21 |
|
19 | 22 | Integer longest = 0;
|
20 |
| - Integer current = 0; |
21 |
| - while (start <= end) { |
22 | 23 |
|
23 |
| - iterate(setOfNums, start, current); |
24 |
| - longest = Math.max(longest, current); |
| 24 | + for (Integer num : setOfNums) { |
| 25 | + int length = iterate(setOfNums, num, 0, lengthMap); |
| 26 | + longest = Math.max(longest, length); |
25 | 27 | }
|
| 28 | + |
| 29 | + return longest; |
26 | 30 | }
|
27 | 31 |
|
28 |
| - public Integer iterate(HashSet<Integer> hashSet, Integer start, Integer currentLength) { |
| 32 | + public Integer iterate(HashSet<Integer> hashSet, int currIndex, int currLength, Map<Integer, Integer> lengthMap) { |
| 33 | + if (lengthMap.containsKey(currIndex)) { |
| 34 | + return lengthMap.get(currIndex); |
| 35 | + } |
29 | 36 |
|
30 |
| - if (hashSet.contains(start)) { |
31 |
| - currentLength++; |
32 |
| - iterate(hashSet, start+1, currentLength); |
| 37 | + if (hashSet.contains(currIndex)) { |
| 38 | + currLength++; |
| 39 | + return iterate(hashSet, currIndex+1, currLength, lengthMap); |
33 | 40 |
|
34 | 41 | } else {
|
35 |
| - // currentLength 를 리턴해야 하나.. |
36 |
| - return start; |
| 42 | + lengthMap.put(currIndex, currLength); |
| 43 | + return currLength; |
37 | 44 | }
|
38 | 45 |
|
39 | 46 | }
|
|
0 commit comments