File tree Expand file tree Collapse file tree 5 files changed +107
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 5 files changed +107
-0
lines changed Original file line number Diff line number Diff line change 1+ //시간복잡도 : O(nlogn)
2+ class Solution {
3+ public boolean containsDuplicate (int [] nums ) {
4+ Arrays .sort (nums );
5+ for (int i = 0 ; i < nums .length - 1 ; i ++) {
6+ if (nums [i ] == nums [i +1 ])
7+ return true ;
8+ }
9+ return false ;
10+ }
11+ }
Original file line number Diff line number Diff line change 1+ //시간복잡도 O(n)
2+ class Solution {
3+ public int rob (int [] nums ) {
4+ if (nums .length == 1 ) {
5+ return nums [0 ];
6+ }
7+
8+ int temp2 = nums [0 ];
9+ int temp1 = Math .max (nums [0 ], nums [1 ]);
10+
11+ for (int i = 2 ; i < nums .length ; i ++) {
12+ int current = Math .max (temp1 , nums [i ] + temp2 );
13+ temp2 = temp1 ;
14+ temp1 = current ;
15+ }
16+
17+ return temp1 ;
18+ }
19+ }
Original file line number Diff line number Diff line change 1+ //시간복잡도: O(n)
2+ import java .util .*;
3+
4+ class Solution {
5+ public int longestConsecutive (int [] nums ) {
6+ Set <Integer > numSet = new HashSet <>();
7+ for (int num : nums ) {
8+ numSet .add (num );
9+ }
10+
11+ int longNum = 0 ;
12+
13+ // 각 숫자에 대해 시퀀스 시작 여부를 확인
14+ for (int num : numSet ) {
15+ // num-1이 없는 경우에만 시퀀스를 시작
16+ if (!numSet .contains (num - 1 )) {
17+ int currentNum = num ;
18+ int currentLong = 1 ;
19+
20+ // 연속된 숫자를 탐색
21+ while (numSet .contains (currentNum + 1 )) {
22+ currentNum ++;
23+ currentLong ++;
24+ }
25+
26+ // 가장 긴 시퀀스를 갱신
27+ longNum = Math .max (longNum , currentLong );
28+ }
29+ }
30+
31+ return longNum ;
32+ }
33+ }
Original file line number Diff line number Diff line change 1+ //시간복잡도: O(n + mlogk)
2+ import java .util .*;
3+ class Solution {
4+ public int [] topKFrequent (int [] nums , int k ) {
5+ Map <Integer , Integer > map = new HashMap <>();
6+
7+
8+ for (int i : nums ) {
9+ map .put (i , map .getOrDefault (i ,0 ) + 1 );
10+ }
11+
12+ PriorityQueue <Map .Entry <Integer , Integer >> pq =
13+ new PriorityQueue <>(Comparator .comparingInt (Map .Entry ::getValue ));
14+
15+ for (Map .Entry <Integer , Integer > entry : map .entrySet ()) {
16+ pq .offer (entry );
17+ if (pq .size () > k ) {
18+ pq .poll (); // Remove the least frequent element
19+ }
20+ }
21+
22+ // Step 3: Extract the elements from the heap
23+ int [] result = new int [k ];
24+ for (int i = k - 1 ; i >= 0 ; i --) {
25+ result [i ] = pq .poll ().getKey ();
26+ }
27+
28+ return result ;
29+
30+ }
31+ }
Original file line number Diff line number Diff line change 1+ //시간복잡도: O(n)
2+ class Solution {
3+ public boolean isPalindrome (String s ) {
4+ s = s .toLowerCase ().trim ();
5+ s = s .replaceAll ("[^a-z0-9]" , "" );
6+
7+ StringBuffer sb = new StringBuffer (s );
8+ String reverse = sb .reverse ().toString ();
9+
10+ return (s .equals (reverse ));
11+
12+ }
13+ }
You can’t perform that action at this time.
0 commit comments