File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ Problem 128 : Longest Consecutive Sequence
3+ Summary :
4+ - for문으로 순회하면서, target에서 뺀 값을 저장한다.
5+ - 저장된 값과 일치하는 인덱스를 만나면 해당 값을 리턴한다.
6+ - 기본 For문이 O(N^2)이라면, 해당 방법의 경우 O(N)이 가능하다.
7+
8+ */
9+ class Solution {
10+ public int longestConsecutive (int [] nums ) {
11+ int max = 0 ;
12+
13+ Set <Integer > set = new HashSet <>();
14+ for (int num : nums ) {
15+ set .add (num );
16+ }
17+ Set <Integer > completeSet = new HashSet <>();
18+ for (int i = 0 ; i < nums .length ; i ++) {
19+ if (!set .contains (nums [i ]-1 ) && !completeSet .contains (nums [i ])){
20+ int sequence = getSequence (nums [i ], set );
21+ max = Math .max (sequence , max );
22+ completeSet .add (nums [i ]);
23+ }
24+ }
25+
26+ return max ;
27+
28+
29+ }
30+
31+ public int getSequence (int startNum , Set <Integer > numSet ) {
32+ int result = 1 ;
33+ while (true ) {
34+ startNum ++;
35+ if (!numSet .contains (startNum )) {
36+ break ;
37+ }
38+ result ++;
39+ }
40+ return result ;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments