알고리즘 [프로그래머스 k번째 수] 문제
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
•
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
•
2에서 나온 배열의 3번째 숫자는 5입니다.배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
1. 배열로 풀기
•
배열을 자르는 방법을 아는지
•
정렬을 할줄 아는지
•
특정 인덱스의 값을 뽑을 수 있는지
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int i = 0; i<commands.length; i++){
int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
answer[i] = temp[commands[i][2]-1];
}
return answer;
}
Java
복사
Java array from to
public class KthTest {
public static void main(String[] args) {
int[] arr = {1, 5, 2, 6, 3, 7, 4};
int[] arr1 = Arrays.copyOfRange(arr, 2-1, 5); //2부터 5까지 해서 5,2,6,3 출력
System.out.println(Arrays.toString(arr1));
}
}
Java
복사
2. 우선순위큐를 이용해서 풀기
•
배열을 잘라서 새로 만들면 메모리를 추가로 쓰게 되는데 배열을 만드는 것을 최소화 하면 메모미를 덜 쓴다.
•
PriorityQueue가 정렬을 해주기 때문에 Sort를 따로 쓰지 않아도 된다.
•
우선순위가 가장 높은 데이터를 가장 먼저 삭제하는 방법
public class KthNumPriorityQueue {
public int[] solution(int[] arr, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
// 우선순위 큐에 from, to까지 넣기
for (int j = commands[i][0]-1; j < commands[i][1]; j++) {
pq.add(arr[j]);
}
// 정렬이 되었기 때문에 뽑기만 한다.
for (int j = 0; j < commands[i][2]; j++) {
answer[i] = pq.poll();
}
}
return answer;
}
public static void main(String[] args) {
KthNumPriorityQueue kthNum = new KthNumPriorityQueue();
int[] arr = new int[]{1, 5, 2, 6, 3, 7, 4};
int[][] commands = new int[][]{{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};.
System.out.println(Arrays.toString(kthNum.solution(arr, commands)));;
}
}
Java
복사
토비의 스프링
DataSource 인터페이스 적용 183p
deleteAll()에 익명 클래스 적용 233p
add()에 익명 클래스 적용 232p
JdbcContext 클래스로 분리 234p
Template Callback 247p
•
excuteSql() - Query를 받아서 PreparedStatement를 만든 후 실행하는 기능
public void executeSql(String sql) throws SQLException {
this.jdbcContext.workWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makePreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(sql);
}
});
}
public void deleteAll() throws SQLException {
this.executeSql("delete from users");
// 쿼리만 넘기게 함
}
Java
복사
public void deleteAll() throws SQLException {
this.jdbcContext.executeSql("delete from users");
} //UserDao.java
Java
복사
public void executeSql(String sql) throws SQLException {
this.workWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makePreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(sql);
}
});
} //JdbcContext.java
Java
복사
JdbcTemplate 적용 262p
UserDao.java
deleteAll()
add()
getCount()
findByud()
getAll()구현
getAllTest() 추가
RowMapper의 중복 제거