월 17,600원
5개월 할부 시다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결자바 코딩테스트 - it 대기업 유제
교육과정 질문드립니다.
answer에 답을 받으면서 출력하면 정답이 맞게 나오는데, 답을 받기만 하면 이상하게 나오네요뭐가 다른거죠???import java.util.*; import java.io.*; class Main { public static ArrayList<Integer>[] graph; public static int[] ind; public String[] solution(String[] subjects, String[] course){ String[] answer = {}; HashMap<String, Integer> map = new HashMap<>(); for(int i=0; i<subjects.length; i++) { map.put(subjects[i], i); } int n=subjects.length; ind = new int[n]; graph = new ArrayList[n]; for(int i=0; i<n;i++) graph[i] = new ArrayList<>(); for(int i=0; i<n; i++) { String[] list = course[i].split(" "); int a = map.get(list[0]); //사후 과목의 밸류값 받기 int b = map.get(list[1]); //사전 과목의 밸류값 받기 graph[b].add(a); ind[a]++; } Deque<Integer> q = new LinkedList<>(); for(int i=0; i<n; i++) { if(ind[i]==0) q.offer(i); } ArrayList<Integer> list = new ArrayList<>(); while(!q.isEmpty()) { int now = q.poll(); list.add(now); for(int next : graph[now]) { ind[next]--; if(ind[next]==0) q.offer(next); } } answer = new String[list.size()]; for(int i=0; i<list.size();i++) { answer[i] = subjects[list.get(i)]; System.out.print(answer[i]+ " "); } return answer; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new String[]{"english", "math", "physics", "art", "music"}, new String[]{"art math", "physics art", "art music", "physics math", "english physics"})); //System.out.println(T.solution(new String[]{"art", "economics", "history", "chemistry"}, new String[]{"chemistry history", "economics history", "art economics"})[0]); //System.out.println(T.solution(new String[]{"math", "science", "music", "biology"}, new String[]{"science music", "math music", "math science", "biology math"})); } }
- 미해결자바 코딩테스트 - it 대기업 유제
미로의 최단거리 탐색(L)질문 드립니다.
아래와 같이 작성했는데, 답이 0이 나옵니다.잘못된 부분이 있을까요?? import java.util.*; import java.io.*; class Main { public static int n,m,L; public static int[][] map ,dist; public static boolean[][] visit; public static int[] dx = {0,0,1,-1}; public static int[] dy = {1,-1,0,0}; public int solution(int[][] board){ int answer = 0; n=board.length; m=board[0].length; map = new int[n][m]; dist = new int[n][m]; visit = new boolean[n][m]; L=0; for(int i=0; i<n;i++) { for(int j=0; j<m; j++) { map[i][j] = board[i][j]; } } bfs(0,0); return answer; } public static int bfs(int r,int c) { Queue<int[]> q =new LinkedList<>(); q.offer(new int[] {r,c}); //0,0대입 visit[r][c] = true; while(!q.isEmpty()) { L++; int len = q.size(); for(int i=0; i<len; i++) { int[] tmp = q.poll(); int nowx = tmp[0]; int nowy = tmp[1]; for(int j=0;j<4;j++) { //상하좌우 탐색 int nx = nowx+dx[j]; int ny = nowy+dy[j]; if(nx>=0 && ny>=0 && nx<n && ny<m) { //맵 범위안이고 if(!visit[nx][ny] && map[nx][ny]==0) { //다음 노드가 방문안햇고, 방문할 수 있다 dist[nx][ny]=L; q.offer(new int[] {nx,ny}); visit[nx][ny] = true; } } } } } return dist[n-1][m-1]; } public static void main(String[] args){ Main T = new Main(); int[][] arr={{0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0}, {1, 1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 0, 0}, {1, 0, 0, 0, 1, 0, 0}, {1, 0, 1, 0, 0, 0, 0}}; System.out.println(T.solution(arr)); } }
- 미해결자바 코딩테스트 - it 대기업 유제
공 굴리기 코드 질문드립니다.
클래스 사용해서 작성했는데, 계속 무한 반복을 도는 것 같습니다. 어디가 잘못된건지 잘 모르겠습니다. import java.util.*; class Node implements Comparable<Node>{ int x; int y; int c; Node(int x,int y, int c){ this.x=x; this.y=y; this.c=c; } @Override public int compareTo(Node o) { return this.c - o.c; } } class Main { public static int n,m; public static int INF = (int)1e9; public static boolean[][] visit; public static int[] dx = {0,0,1,-1}; public static int[][] map,dist; public static int[] dy = {1,-1,0,0}; public static int dij(int s1,int s2,int e1, int e2) { PriorityQueue<Node> q =new PriorityQueue<>(); q.offer(new Node(s1,s2,0)); dist[s1][s2] = 0; while(!q.isEmpty()) { Node tmp = q.poll(); int nowx = tmp.x; int nowy = tmp.y; int nowcnt = tmp.c; if(nowcnt>dist[nowx][nowy]) continue; for(int i=0; i<4; i++) { int nx = nowx+dx[i]; int ny = nowy+dy[i]; while(nx>=0 && ny>=0 && nx<n && ny<m && map[nx][ny]==0) { //맵의 범위안을 만족하면 계속 같은 방향으로 이동 nx+=dx[i]; ny+=dy[i]; nowcnt++; } //벽에 막혔다. nx-=dx[i]; //이전 칸으로 이동 ny-=dy[i]; nowcnt--; //이전 칸으로 이동했으니까 갯수 하나 감소 if(dist[nx][ny]>nowcnt) { //우선순위 큐에 넣기 dist[nx][ny] = nowcnt; q.offer(new Node(nx,ny,dist[nx][ny])); } } } //답 출력 if(dist[e1-1][e2-1]==Integer.MAX_VALUE) return -1; return dist[e1-1][e2-1]; } public int solution(int[][] board, int[] s, int[] e){ int answer = 0; n=board.length; m=board[0].length; dist = new int[n][m]; for(int i=0; i<n; i++) Arrays.fill(dist[i], INF); map = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m;j++) { map[i][j] = board[i][j]; } } answer = dij(s[0],s[1],e[0],e[1]); return answer; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[][]{{0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 0}, {1, 0, 0, 0, 0, 0}}, new int[]{1, 0}, new int[]{4, 5})); System.out.println(T.solution(new int[][]{{0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 0}, {1, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 2})); System.out.println(T.solution(new int[][]{{1, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 0, 1, 1}, {0, 0, 0, 0, 0}}, new int[]{0, 3}, new int[]{4, 2})); System.out.println(T.solution(new int[][]{{0, 1, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {0, 1, 1, 0, 1, 1}, {0, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 5})); System.out.println(T.solution(new int[][]{{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 3})); } }
- 미해결자바 코딩테스트 - it 대기업 유제
팰린드롬의 경우의 수 질문드립니다.
저는 입력값이 크지가 않아서 가능한 문자열의 길이가 n이 되면 팰린드롬을 체크해서 중복방지를 위해 해시셋에 만족하는 문자열을 담는 걸로 구현을 했습니다.근데 재귀함수 안에서는 출력값이 잘 나오는거 같은데, 그걸 해시에 담았는데, 해시의 크기가 0으로 나옵니다. 무엇이 잘못된건가요??? import java.util.*; class Main { public static boolean[] visit; public static int n; public static String[] ll; public static HashSet<String> ans = new HashSet<>(); public String[] solution(String s){ String[] answer = {}; dfs(0,""); n=s.length(); visit = new boolean[n]; ll = s.split(""); //s를 문자열 배열로 분리 ans = new HashSet<>(); answer = new String[ans.size()]; System.out.print(answer.length); return answer; } public static void dfs(int L, String str) { //문자열 만들어주기 if(L==n) { if(check(str)) { //팰린드롬인지 체크 //System.out.println(str); ans.add(str); } else return; } else { for(int i=0; i<ll.length;i++) { //i번째 문자 썼는지 확인하면서 문자열 만들어주기 if(!visit[i]) { visit[i] = true; dfs(L+1,str+ll[i]); visit[i] = false; } } } } public static boolean check(String str) { //팰린드롬인지 체크 String[] list = str.split(""); int lt=0; int rt= list.length-1; while(lt<rt) { if(list[lt].equals(list[rt])) { lt++; rt--; } else return false; } return true; } public static void main(String[] args){ Main T = new Main(); System.out.println(Arrays.toString(T.solution("aaaabb"))); System.out.println(Arrays.toString(T.solution("abbcc"))); System.out.println(Arrays.toString(T.solution("abbccee"))); System.out.println(Arrays.toString(T.solution("abbcceee"))); System.out.println(Arrays.toString(T.solution("ffeffaae"))); } }
- 미해결자바 코딩테스트 - it 대기업 유제
바둑대회 조합 코드 작성질문드립니다.
조합으로 이렇게 작성했는데, 답이 다르게 나옵니다.잘못 생각한 부분이 있을까요?? import java.util.*; class Main { public static boolean[] visit; public static int answer; public static int[] white,black; public static int sum1,sum2,n; public int solution(int[][] cans){ int answer = Integer.MAX_VALUE; n=cans.length; white = new int[n]; black = new int[n]; visit = new boolean[n]; int i=0; for(int[] x : cans) { //흰색돌, 검정돌 분리해주기 white[i] = x[0]; black[i] = x[1]; i++; } dfs(0,0); //조합 탐색 시작 return answer; } public static void dfs(int L, int s) { if(L==n/2) { sum1=0; sum2=0; for(int i=0; i<n; i++) { //방문했던곳은 흰색 돌, 그렇지 않은 곳은 검은돌 if(visit[i]) sum1+=white[i]; //흰색돌들의 합 else sum2+=black[i]; //검정색 돌들의 합 } answer = Math.min(answer, Math.abs(sum1-sum2)); } else { for(int i=s; i<n; i++) { if(!visit[i]) { visit[i] = true; dfs(L+1, i+1); visit[i] = false; } } } } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[][]{{87, 84}, {66, 78}, {94, 94}, {93, 87}, {72, 92}, {78, 63}})); System.out.println(T.solution(new int[][]{{10, 20}, {15, 25}, {35, 23}, {55, 20}})); System.out.println(T.solution(new int[][]{{11, 27}, {16, 21}, {35, 21}, {52, 21}, {25, 33},{25, 32}, {37, 59}, {33, 47}})); } }
- 미해결자바 코딩테스트 - it 대기업 유제
멀티태스킹 문제 질문드립니다.
만약 강의에서처럼 규칙을 찾지 못해서큐로 구현했는데, 이렇게 구현하면 안되는건가요??? import java.util.*; class Node{ int number; //해당 작업의 작업시간 int idx; //작업 번호 Node(int number, int idx){ this.number = number; this.idx = idx; } } class Main { public static Queue<Node> q= new LinkedList<>(); public int solution(int[] tasks, long k) { int answer = 0; for(int i=0; i<tasks.length; i++) { q.offer(new Node(tasks[i],i+1)); //1 2 3, 각 작업 번호들 대입 } long time=0; while(!q.isEmpty()) { Node tmp = q.poll(); int nownumber = tmp.number; int nowwork = tmp.idx; nownumber--; time++; if(time==k) { answer = nowwork; break; } if(nownumber!=0) { q.offer(new Node(nownumber, nowwork)); } } return answer; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[]{1, 2, 3}, 5)); System.out.println(T.solution(new int[]{8, 5, 2, 9, 10, 7}, 30)); System.out.println(T.solution(new int[]{8, 9, 12, 23, 45, 16, 25, 50}, 100)); } }
- 미해결자바 코딩테스트 - it 대기업 유제
심사위원 시간복잡도
이렇게 작성했는데, 시간 복잡도에 걸리지 않게 작성한것이 맞나요?? import java.util.*; class Main { public int solution(int[] score, int k){ int answer = 0; Arrays.sort(score); int sum=0; ArrayList<Integer> ans = new ArrayList<>(); //k개 원소를 담을 리스트 for(int i=0; i<score.length; i++) { //배열을 처음부터 탐색한다. int diff = score[i+k-1] - score[i]; //앞 뒤 원소의 차이를 구한다. if(diff<=10) { //만약 그 차이가 10이하이면 int cnt=0; //개수를 세기위한 변수 int j=i; //i번째 원소부터 시작해서 리스트에 담는다. while(true) { //10이하의 경우에서 제일 첫번째로 찾는게 정답이다. if(cnt==k) break; //k개만큼 담았으면 반복문 멈춘다. ans.add(score[j++]); //답에 해당하는 원소들을 ans에 담아준다. cnt++; } break; } } sum=0; //원소들의 합계를 구하기 위한 변수 for(int i=0; i<ans.size(); i++) { sum+=ans.get(i); } answer = (int)sum/k; return answer; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[]{99, 97, 80, 91, 85, 95, 92}, 3)); System.out.println(T.solution(new int[]{92, 90, 77, 91, 70, 83, 89, 76, 95, 92}, 4)); System.out.println(T.solution(new int[]{77, 88, 78, 80, 78, 99, 98, 92, 93, 89}, 5)); System.out.println(T.solution(new int[]{88, 99, 91, 89, 90, 72, 75, 94, 95, 100}, 5)); } }
- 미해결자바 코딩테스트 - it 대기업 유제
이진수 정렬 문제 질문드립니다.
이진수를 나타내는 Integer.toBinary()를 사용해서 사용자 정렬로 했는데, 답이 다르게 나옵니다. 라이브러리 함수를 사용하면 안되는 건가요?? import java.util.*; class Node implements Comparable<Node>{ int idx; //배열의 원소값 int cnt; //1의 개수 Node(int idx, int cnt){ this.idx = idx; this.cnt = cnt; } @Override public int compareTo(Node o) { if(this.cnt==o.cnt) return this.idx - o.idx; //1의 개수가 같으면 배열의 원소를 기준으로 오름차순 else return this.cnt- o.cnt; //그게 아니면 1의 개수가 작은것을 기준으로 오름차순 } } class Main { public static ArrayList<Node> list = new ArrayList<>(); public int[] solution(int[] nums){ int[] answer; for(int i=0; i<nums.length; i++) { String s = Integer.toBinaryString(nums[i]); //2진수로 만들어주기 list.add(new Node(nums[i], count(s))); } Collections.sort(list); //조건에 맞게 정렬 answer = new int[list.size()]; for(int i=0; i<list.size(); i++) { answer[i] = list.get(i).idx; } return answer; } public static int count(String ss) { //1의 개수를 세주는 메소드 int cnt=0; String[] list = ss.split(""); for(int i=0; i<list.length; i++) { if(list[i].equals("1")) cnt++; } return cnt; } public static void main(String[] args){ Main T = new Main(); System.out.println(Arrays.toString(T.solution(new int[]{5, 6, 7, 8, 9}))); System.out.println(Arrays.toString(T.solution(new int[]{5, 4, 3, 2, 1}))); System.out.println(Arrays.toString(T.solution(new int[]{12, 5, 7, 23, 45, 21, 17}))); } }
- 미해결자바 코딩테스트 - it 대기업 유제
회장선거 질문드립니다.
vote의 밸류값을 꼭 HashSet으로 잡는 방법 말고는 없는건가요??
- 미해결자바 코딩테스트 - it 대기업 유제
서로 다른 빈도수 만들기
public int solution(String s){ int answer = 0; HashMap<String, Integer> map = new HashMap<>(); HashSet<Integer> hs = new HashSet<>(); //유일하게 존재해야한다 => 해시셋 사용 String[] list = s.split(""); for(int i=0; i<list.length; i++) { map.put(list[i], map.getOrDefault(list[i], 0)+1); } for(String x : map.keySet()) { int check = map.get(x); while(hs.contains(check)) { //셋에 이미 숫자가 있으면 하나를 감소 check--; if(check==0) { //0은 넣지 않는다. answer++; break; } answer++; } hs.add(check); } return answer; }이처럼 작성했는데 답은 모두 맞게 출력되는데, 강사님이 작성하신 알고리즘이랑 동일한 건가요???
- 미해결자바 코딩테스트 - it 대기업 유제
최대길이 바이토닉 수열 문제 질문드립니다.
저는 투포인터로 생각하고 각 경우의 수에 따라 바이토닉을 판별하는 걸로 했는데, 답이 다르긴한데 이렇게 구현하면 안되는 건가요??? public int solution(int[] nums){ int answer = 0; //다음 숫자가 지금 숫자보다 커여한다 //반복하면 안됨 //증가하다가 줄어든다 (정답 후보) //같은 수가 나오면 안된다. int cnt=0; boolean flag = false; //바이토닉 여부를 판별하기 위한 boolean변수 int ans = 0; int lt=0; for(int rt=1; rt<nums.length; rt++) { if(nums[lt]<nums[rt]) { //다음 숫자가 더 크면 바이토닉 가능 lt++; flag = true; //바이토닉이다 continue; } else if(nums[lt]==nums[rt]) { //다음 숫자랑 지금 숫자랑 같으면 바이토닉 아니다. lt++; if(flag) { //만약 이전까지 바이토닉이였다면 길이 구해주기 cnt = rt-lt+1; } flag = false; //바이토닉 판별을 초기화 continue; } else if(nums[lt]>nums[rt] && flag) { //다음 숫자가 지금보다 작고 바이토닉이면 지금까지의 길이를 구해줌 cnt = rt-lt+1; } else if(nums[lt]>nums[rt] && !flag) { //다음 숫자가 지금보다 작지만 바이토닉이 아니였다면 무시 lt++; continue; } ans = Math.max(ans, cnt); //최대 길이 갱신 } System.out.print(ans); return answer; }
- 해결됨자바 코딩테스트 - it 대기업 유제
청소 문제 dx,dy배열 방향벡터 x,y 바뀐거같은데 맞나요??
3시방향이면 x축을 움직여야되는데강사님 설명은 y축이 움직이는걸로 되어있습니다.배열이 거꾸로 된거같아 매우 헷갈립니다.답변 부탁드립니다.
- 미해결자바 코딩테스트 - it 대기업 유제
잃어버린 강아지 질문드립니다.
초기에 현수 위치와 강아지 위치를 큐에 넣어주고 탐색했는데, 큐에 넣고 탐색하면 안되는건가요??? import java.io.*;import java.util.*;class Node { int x; int y; Node(int x,int y){ this.x=x; this.y=y; }} public class Main { public int solution(int[][] board){ int[] dx = {-1, 0, 1, 0}; int[] dy = {0, 1, 0, -1}; int n =board.length; int m=board[0].length; int d1=0, d2=0; Queue<Node> huyn = new LinkedList<>(); Queue<Node> dog = new LinkedList<>(); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(board[i][j]==2) { huyn.add(new Node(i,j)); } if(board[i][j]==3) { dog.add(new Node(i,j)); } } } int time=0; while(time<10000) { time++; boolean flag1=true, flag2=true; Node ddog = dog.poll(); Node h = huyn.poll(); int nxh = h.x+dx[d1]; //현수의 다음 노드 int nyh = h.y+dy[d1]; int dogx = ddog.x+dx[d2]; int dogy = ddog.y+dy[d2]; if(nxh<0 || nyh<0 || nxh>=n || nyh>=m || board[nxh][nyh]==1) { d1 = (d1+1)%4; flag1 = false; } if(dogx<0 || dogy<0 || dogx>=n || dogy>=m || board[dogx][dogy]==1) { d2 = (d2+1)%4; flag2 = false; } if(flag1) { huyn.add(new Node(nxh,nyh)); } if(flag2) { dog.add(new Node(dogx, dogy)); } if(nxh==dogx && nyh==dogy) { return time; } } return 0; } public static void main(String[] args){ Main T = new Main(); int[][] arr1 = { {0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 2, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 3, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 0} }; System.out.println(T.solution(arr1)); int[][] arr2 = { {1, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 2, 1}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 3} }; System.out.println(T.solution(arr2)); } }
- 미해결자바 코딩테스트 - it 대기업 유제
풀이질문입니다.
안녕하세요. 해시를 이용한 풀이 잘 보았습니다!!.저는 혹시 리스트를 이용해서 풀어보았는데 괜찮은 풀이 방식일까요?? public static int[] solution(int[] nums){ int n = nums.length; int[] answer = new int[n / 2]; ArrayList<Integer> ans = new ArrayList<>(); for(int x : nums){ ans.add(x); } Collections.sort(ans); for(int x : nums){ for(int i=0;i<ans.size();i++){ if(x*2 == ans.get(i)){ ans.remove(i); break; } } } for(int i=0;i<n/2;i++){ answer[i] = ans.get(i); } return answer; }
- 미해결자바 코딩테스트 - it 대기업 유제
[3.자료구조 활용 - 5번 cpu스케쥴링] 입력예제 1번 설명 확인
안녕하세요. 김태원 강사님![질문]입력예제 설명에 오타가 있는 것 같아서 확인 차 문의드립니다.[문제]3.자료구조 활용 챕터에 5번 cpu스케쥴링문제입력예제 1번 설명 :1초에 1번 작업을 실행해서 3초에 끝냅니다.3초에 3번 작업을 실행해서 4초에 끝냅니다.4초에 2번 작업을 실행해서 6초에 끝냅니다.-> (확인필요) 4초에 0번 작업을 실행해서 7초에 끝냅니다.6초에 0번 작업을 실행해서 9초에 끝냅니다.-> (확인필요) 8초에 2번 작업을 실행해서 10초에 끝냅니다. [요청]입력예제 1번 설명에 '(확인필요)표시한 부분의 설명'이 맞는 지 답변 부탁드립니당! ps. 코딩테스트 준비가 막막했는데 강사님의 좋은 강의 덕분에 준비할 수 있게 되어서 너무 감사합니다 :)
- 해결됨자바 코딩테스트 - it 대기업 유제
sorting & thinking 7번 최소 회의실 개수
안녕하세요 강사님 자바 알고리즘 입문 강좌에 이어 이번 강좌 까지 들으며 많은 도움을 받고 있는 수강생입니다. 우선 양질의 강의를 제공해주신 것에 감사드립니다.이번 문제에서 저는 아래와 같이 코드를 작성했습니다. 자료구조 파트 마지막 문제와 유사하다고 생각했서 아래와 같이 풀었습니다. 저는 해법 영상에서와 같은 논리라고 생각하는데 혹시 논리적 오류가 있을까요? public int solution(int[][] meetings) { int answer = 0; PriorityQueue<Meeting> pq = new PriorityQueue<>(); Arrays.sort(meetings, (a, b) -> a[0] - b[0]); for (int[] meeting : meetings) { if (pq.isEmpty()) { pq.add(new Meeting(meeting[1], answer)); answer++; } else { if (pq.peek().end <= meeting[0]) { pq.add(new Meeting(meeting[1], pq.poll().room)); } else { pq.add(new Meeting(meeting[1], answer)); answer++; } } } return answer; }
- 미해결자바 코딩테스트 - it 대기업 유제
문제 2번째 test case 질문
안녕하세요 선생님. 문제 조건상 "서로가 이득이 생기지 않으면 교환하지 않는 학생도 있습니다" 이 문장을 "서로가 이득이 생기지 않으면 두 학생 은 교환하지 않는다" 로 해석하는게 맞을까요?왜냐하면 교환이라는건 양쪽다 주고 받는게 있어야 하니깐 , 둘다 주고 받거나 / 둘다 주고받지 않거나 로 이해해서 위와 같이 생각하였습니다.
- 해결됨자바 코딩테스트 - it 대기업 유제
블로그 문제 첨부 가능 여부
블로그에 학습한 내용을 올리고 싶은데문제 자료를 캡쳐해서 사용해도 괜찮나요??!
- 해결됨자바 코딩테스트 - it 대기업 유제
잃어버린 강아지 코드 질문
Thing이라는 클래스를 생성하여 멤버 변수로 x, y, d를 가지게 했습니다.처음 for문을 돌면서, dog과 person이라는 객체를 생성해서 각자의 x,y,d값을 가지도록 생성자를 구현했습니다.그 외의 로직은 강의와 거의 유사한데, 첫번째 테스트 케이스는 51이 나오지만 두번째 테스트케이스가 0으로 나오고 있습니다.코드 첨부하겠습니다.class Thing { int x; //x 좌표 int y; //y 좌표 int d; //바라보는 위치 public Thing(int x, int y, int d) { this.x = x; this.y = y; this.d = d; } } public class Code04 { public int solution(int[][] board){ int[] dx = {-1, 0, 1, 0}; int[] dy = {0, 1, 0, -1}; Thing person = null; Thing dog = null; int time = 0; //사람과 강아지의 위치 좌표를 찾는다. for(int i=0; i<board.length; i++) { for(int j=0; j<board[i].length; j++) { if(board[i][j] == 2) { person = new Thing(i, j, 0); } if(board[i][j] == 3) { dog = new Thing(i, j, 0); } } } if(person == null || dog == null) { // 2 혹은 3이 존재하지 않는 경우 return 0; } while(time < 10000) { time++; int px = person.x + dx[person.d]; int py = person.y + dy[person.d]; int dogX = dog.x + dx[dog.d]; int dogY = dog.y + dy[dog.d]; boolean flagP = true; boolean flagD = true; if(px == dogX && py == dogY) { return time; } if(!isValidXY(px, py, board)) { person.d = (person.d + 1) % 4; flagP = false; } if(!isValidXY(dogX, dogY, board)) { dog.d = (dog.d + 1) % 4; flagD = false; } if(flagP) { person.x = px; person.y = py; } if(flagD) { dog.x = dogX; dog.y = dogY; } } return 0; } private boolean isValidXY(int x, int y, int[][] board) { return x >= 0 && y >= 0 && x < board.length && y < board.length && board[x][y] != 1; } public static void main(String[] args){ Code04 T = new Code04(); int[][] arr1 = { {0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 2, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 3, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 0} }; System.out.println(T.solution(arr1)); int[][] arr2 = { {1, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 2, 1}, {0, 0, 0, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 3} }; System.out.println(T.solution(arr2)); } }
- 미해결자바 코딩테스트 - it 대기업 유제
우선순위 큐를 활용해도 되나요?
우선순위 큐를 써서 문제를 풀었는데 채점 지원이 안되다 보니 제 논리에 허점이 있나 확인차 질문드립니다.도착지 정보와 현재 지점까지 오는데 걸리는 비용, 환승 횟수 정보를 가지고 있는 Path 클래스를 이용했습니다.static class Path implements Comparable<Path>{ int end, cost, t; public Path(int end, int cost, int t) { this.end = end; this.cost = cost; this.t = t; } @Override public int compareTo(Path p) { return this.cost - p.cost; } } public int solution(int n, int[][] flights, int s, int e, int k){ int answer = 0; ArrayList<ArrayList<Path>> list = new ArrayList<>(); for(int i = 0; i < n; i++) { list.add(new ArrayList<>()); } for (int[] flight : flights) { int start = flight[0]; int end = flight[1]; int cost = flight[2]; list.get(start).add(new Path(end, cost, 0)); } PriorityQueue<Path> pq = new PriorityQueue<>(); for (Path path : list.get(s)) { pq.add(path); } while(!pq.isEmpty()) { Path cur = pq.poll(); if(cur.t <= k && cur.end == e) { answer = cur.cost; break; } for (Path path : list.get(cur.end)) { pq.add(new Path(path.end, path.cost + cur.cost, cur.t + 1)); } } return answer == 0 ? -1 : answer; } 클래스를 만들지 않고 List<int[]> 로 만드시는 이유도 궁금합니다. 배열로 만들면 int[0]이 무엇이 의미하는지 알기 힘들지만, 클래스로 만들면 end, cost 등 변수 이름으로 표현하기더 쉬워서 좋은 것 같은데 알고리즘에는 부적합한가요?