기본 콘텐츠로 건너뛰기

2022의 게시물 표시

코딩 테스트 - 정수 삼각형

대박! 라이브 코딩테스트에서 나온 문제임 (<<<랑 >>> 짜는데 오래 걸렸었음... ) 카메라 켜놓고 봤던 시험이라 손발이 부들부들... 아무튼 보통 이렇게 짤 것이다... ↓ 요롷게... package programmers ; public class 정수삼각형_221231 {     public static void main ( String [] args ) {         int [][] triangle = {{ 7 }, { 3 , 8 }, { 8 , 1 , 0 }, { 2 , 7 , 4 , 4 }, { 4 , 5 , 2 , 6 , 5 }};         System . out . println ( solution ( triangle ));     }         public static int solution ( int [][] triangle ) {         int answer = 0 ;         int len = triangle . length ;         int [][] arr = new int [ len ][ len ];                         for ( int i = 0 ; i < len ; i ++) {             if ( i == 0 ){                 arr [ 0 ][ 0 ] = triangle [ 0 ][ 0 ];             } else {                 // <>                 for ( int j = 1 ; j <= i ; j ++) {                     arr [ i ][ j ] = Math . max ( arr [ i - 1 ][ j ], arr [ i - 1 ][ j - 1 ]) + triangle [ i ][ j ];                 }                 // <<<

코딩 테스트 - MaxSliceSum

package codility ; public class MaxSliceSum_221231 {     public static void main ( String [] args ) {         int [] A  = { 3 , 2 ,- 6 , 4 , 0 };         System . out . println ( solution ( A ));     }           public static int solution ( int [] A ) {                     if ( A . length == 1 ){             return A [ 0 ];         }           int max = A [ 0 ];         int temp = A [ 0 ];         int answer = A [ 0 ];         for ( int i = 1 ; i < A . length ; i ++){             max = Math . max ( A [ i ], temp + A [ i ]);   //여기를 A[i]  +A[i+1]로 짜면 오류남!             temp = max ;             answer = Math . max ( max , answer );         }         return answer ;     } } temp 값을 두는 것이 포인트... (temp 없이 중간 값 둬도 될 것 같긴 했는데 시간복잡도 초과됨!) 새해 복 많이 받으세요. (2022-12-31!)

코딩 테스트 - MaxProfit

Maximum slice problem 으로 넘어왔습니다! 재미있...는...? codility의 영어공부...★  문제에 주식 얘기가 나와서 너무나 멜랑콜리해집니다. 저의 삼성 주식은 고등어가 되었고, LG 주식은 갈치가 되었기 때문이지오... ↓ 하하 package codility ; import java . util . Arrays ; public class MaxProfit_221230 {     public static void main ( String [] args ) {         int [] A = { 23171 , 21011 , 21123 , 21366 , 21013 , 21367 };         System . out . println ( solution ( A ));     }     public static int solution ( int [] A ) {         if ( A . length == 1 || A . length == 0 ){             //0~1은 이익이 없으니 끝냄             return 0 ;         }         int answer = 0 ;           int min = Arrays . stream ( A ). min (). getAsInt ();         int flag = 0 ;                 for ( int i = 0 ; i < A . length ; i ++){             if ( A [ i ] == min ){                 if ( i == A . length - 1 ){                     //마지막이니 종료                     return 0 ;                 } else {                     flag = i ;                     break ;              

코딩 테스트 - 이중우선순위큐

핵심 :  reverse를 안 쓰면 굉장히 속도가 느립니다! (풀리긴 합니다.) List만 갖고 풀어도 풀리긴 합니다 ← 근데 이름 자체가 이중우선순위큐라... ㅎ 굳이 PriorityQueue를 안 쓰고 max랑 min 을 쓰면 풀리긴 하나 속도가 느립니다! 시간 복잡도 관련 문제가 아니라 풀리는 게 맞긴 한데 속도가 문제임! package programmers ; import java . util . Arrays ; import java . util . Collections ; import java . util . PriorityQueue ; public class 이중우선순위큐_221230 {     public static void main ( String [] args ) {         //String [] operations = {"I 16", "I -5643", "D -1", "D 1", "D 1", "I 123", "D -1"};         String [] operations = { "I -45" , "I 653" , "D 1" , "I -642" , "I 45" , "I 97" , "D 1" , "D -1" , "I 333" };         int [] arr = solution ( operations );         System . out . println ( Arrays . toString ( arr ));     }         public static int [] solution ( String [] operations ) {         /*             16과 -5643을 삽입합니다.      

코딩 테스트 - EquiLeader

package codility ; import java . util . Arrays ; import java . util . Collections ; public class EquiLeader_221229 {     public static void main ( String [] args ) {         int [] A = { 4 , 3 , 4 , 4 , 4 , 2 };         System . out . println ( solution ( A ));     }         public static int solution ( int [] A ) {         int answer = 0 ;         Integer [] A_top = Arrays . stream ( Arrays . copyOfRange ( A , 0 , A . length / 2 )). boxed (). toArray ( Integer [] ::new );         Integer [] A_bottom = Arrays . stream ( Arrays . copyOfRange ( A , A . length / 2 , A . length )). boxed (). toArray ( Integer [] ::new );         Arrays . sort ( A_top );         Arrays . sort ( A_bottom );         int at , ab ;         if ( A_top [ A_top . length - 1 ] == A_bottom [ A_bottom . length - 1 ]){             at = Collections . frequency ( Arrays . asList ( A_top ), A_top [ A_top . length - 1 ]);             ab = Collections . frequency ( Arrays . asList ( A_bottom ), A_bot

코딩 테스트 - 캐시

package programmers ; import java . util . LinkedList ; public class 캐시_221229 {     public static void main ( String [] args ) {         int cacheSize = 3 ;         String [] cities = { "Jeju" , "Pangyo" , "Seoul" , "NewYork" , "LA" , "Jeju" , "Pangyo" , "Seoul" , "NewYork" , "LA" };         System . out . println ( solution ( cacheSize , cities ));     }     public static int solution ( int cacheSize , String [] cities ) {         //캐시 히트랑 캐시 미스를 구현하면 됨         //LRU - 가장 오랫동안 참조하지 않은 페이지를 캐시에서 교체하는 것         // cache hit일 경우 실행시간은 1이다.         // cache miss일 경우 실행시간은 5이다.         int answer = 0 ;         String temp = null ;         if ( cacheSize == 0 ){             answer = cities . length * 5 ; //cache miss인 경우 실행시간은 5             return answer ;         }         LinkedList < String > queue = new LinkedList <>();         for ( int i = 0 ;

코딩 테스트 - 위장

 위장이라고 해서 소화 기관을 생각했더니 스파이였다! (약한 실망) 이거는 어제처럼 짜고 나중에 찾아보니 getOrDefault가 있어서 이걸로 변경함! 땡큐! package programmers ; import java . util . HashMap ; public class 위장_221228 {     public static void main ( String [] args ) {         String [][] clothes = {{ "yellow_hat" , "headgear" }, { "blue_sunglasses" , "eyewear" }, { "green_turban" , "headgear" }};         int ans = solution ( clothes );         System . out . println ( "답 : " + ans );     }     public static int solution ( String [][] clothes ) {         //옷이 많이 없는 스파이         int answer = 1 ;         HashMap < String , Integer > map = new HashMap <>();         for ( int i = 0 ; i < clothes . length ; i ++){                         map . put ( clothes [ i ][ 1 ], map . getOrDefault ( clothes [ i ][ 1 ], 0 )+ 1 );             //getOrDefault 땡큐!             //System.out.println(clothes[i][1] + " " + map.get(clothes[i][1]))

코딩 테스트 - Dominator

어제 거랑 이어서 try! Dominator가 뭔가 했습니다. 이건 사실 인덱스 위치도 같이 저장해 주면 되겠지만 그냥 for문 한 번 더 돌려서 해결. package codility ; import java . util . HashMap ; public class Dominator_221228 {     public static void main ( String [] args ) {         int [] A = { 3 , 4 , 3 , 2 , 3 ,- 1 , 3 , 3 };         System . out . println ( solution ( A ));     }     public   static int solution ( int [] A ) {         // Implement your solution here         int answer = - 1 ;         //중복값이 배열 사이즈의 절반 이상 존재하면 그게 도미네이터임         HashMap < Integer , Integer > map = new HashMap <>();         for ( int i : A ){             if ( map . get ( i ) != null ){                 //있으면                 map . put ( i , ( int ) map . get ( i ) + 1 );             } else {                 map . put ( i , 1 );             }         }         for ( Integer key : map . keySet ()){             if ( map . get ( key ) > A . length / 2 ){                 answer = key ;                 break ;             }    

코딩 테스트 - H-Index

package programmers ; import java . util . Arrays ; public class H_Index_221227 {     public static void main ( String [] args ) {         int [] citations = { 3 , 0 , 6 , 1 , 5 };         System . out . println ( solution ( citations ));     }     public static int solution ( int [] citations ) {                 int answer = 0 ;         int n = citations . length ;         int h = 0 ;         int [] arr = citations . clone ();         Arrays . sort ( arr );                         for ( int i = 0 ; i < n ; i ++){             h = n - i ; //논문 개수             if ( arr [ i ] >= h ){                 //논문보다 인용수가 크거나 같으면                 answer = h ;                 break ;             }         }         return answer ;     }     } 애써서 풀어도...똑똑박사가 너무 많습니다 중간에 끊지 않고 Math 함수 사용해서 비교 하는 방식!

코딩 테스트 - StoneWall

대화를 나누다 11시 52분이 되어 황급히 코딩 테스트 도전! package codility ; import java . util . Stack ; public class StoneWall_221227 {     public static void main ( String [] args ) {         int [] H = { 8 , 8 , 5 , 7 , 9 , 8 , 7 , 4 , 8 };         System . out . println ( solution ( H ));     }     public static int solution ( int [] H ) {         int answer = 0 ;         Stack < Integer > stack = new Stack <>();         Integer temp = 0 ;         for ( int i = 0 ; i < H . length ; i ++) {             while (! stack . isEmpty ()) {                 //안 비었으면 돌린다!                 temp = stack . pop ();                 //일단 pop 해줌! (peek 대신 pop 해버림!)                 if ( temp == H [ i ]) {                     //똑같으면 넣어줌!                     stack . push ( temp );                     break ;                 } else if ( H [ i ] > temp ) {                     //더 크면 temp랑 새로운 애를 넣어줌!                     stack . push ( temp );                     stack . push ( H

코딩 테스트 - 괄호 회전하기

package programmers ; import java . util . Stack ; public class 괄호회전하기_221226 {     public static void main ( String [] args ) {         String s = "()(" ;         System . out . println ( "ㅇㅅㅇ" + solution ( s ));     }     public static int solution ( String s ) {         int answer = 0 ;         for ( int i = 0 ; i < s . length (); i ++){             System . out . println ( i );             answer = answer + bracelet ( s . substring ( i , s . length ()) + s . substring ( 0 , i ));         }         return answer ;     }     public static int bracelet ( String temp ){         int answer = 1 ;         char [] arr = temp . toCharArray ();         Stack < Character > stack = new Stack <>();         int counter = 0 ;         for ( int i = 0 ; i < temp . length (); i ++){             switch ( arr [ i ]){                 case '(' :                     counter --;                     stack . add ( '(&#

코딩 테스트 - Nesting

 그러니까 그냥 괄호 문제임... (근데 좀 더 쉬운) 이거 Stack을 안쓰고 answer ++ -- 로도 풀 수 있는데 그러면 max value 쪽 오류가 난당. if문 한 단계 더 줄인 버전 ↓  package codility ; import java . util . Stack ; public class Nesting_221226 {     public static void main ( String [] args ) {         String S = "()" ;         solution ( S );         System . out . println ();     }     public static int solution ( String S ) {         Stack < Character > stack = new Stack <>();         char [] arr = S . toCharArray ();         for ( int i = 0 ; i < S . length (); i ++){             if ( arr [ i ] == '(' ){                 stack . add ( '(' );             } else if ( stack . size () == 0 || stack . pop () == arr [ i ]){                 return 0 ;             }         }         int answer = 1 ;         if ( stack . size () > 0 ){             answer = 0 ;         }         return answer ;     } }

코딩 테스트 - Fish

package codility ; import java . util . Stack ; public class Fish_221225 {     /*            */     public static void main ( String [] args ) {         int [] A = { 4 , 3 , 2 , 1 , 5 };         int [] B = { 0 , 1 , 0 , 0 , 0 };         /*          * 4 : 살아남음          * 3 : 아직 살아있음          * 2 : 3을 만나서 몰살          * 1 : 3을 만나서 몰살          * 5 : 3은 5를 만나서 몰살          * -> 이게 물고기 마리 수가 아니라 살아남은 개수만 세면 되는 게 포인트였음          */         int ans = solution ( A , B );         System . out . println ( ans );     }     public static int solution ( int [] A , int [] B ) {         int answer = 0 ;         //0 : 상류로 가는 것         //1 : 하류로 가는 것         Stack < Integer > stack = new Stack <>();         int temp = 0 ;         int fishCount = 0 ;         for ( int i = 0 ; i < A . length ; i ++){             if ( B [ i ] == 1 ){                 //1이 적으니까 밑으로 가는 애만 저장한다.                 //System.out.println("물고기 저장" + A[i]);                 stack .

코딩 테스트 - 최고의 집합

package programmers ; import java . util . Arrays ; public class 최고의집합_221225 {     public static void main ( String [] args ) {         int n = 2 ;         int s = 9 ;         solution ( n , s );     }     public static int [] solution ( int n , int s ) {         //중간쯤 값이 곱했을때 제일 큼         int [] answer = new int [ n ];         if ( n > s ){             return new int [] {- 1 };         } else {                         int div = s / n ; // 9 /2             int rem = s % n ; //9 % 2             for ( int i = 0 ; i < n ; i ++){                 if ( i >= ( n - rem )){                     answer [ i ] = div + 1 ;                 } else {                     answer [ i ] = div ;                 }             }         }         return answer ;     } }   이렇게 짜면 굳이 정렬 안 해도 되기 때문에 시간 복잡도 통과! (Arrays.sort 로 짜서 시간복잡도 통과 못 해서 수정...)