문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음 작성한 코드
def solution(array, commands):
answer = []
for com in commands:
new_arr = sorted(array[com[0]-1:com[1]])[com[2]-1]
new_arr.sort()
answer.append(new_arr)
return answer
n번째 수라면 배열의 인덱스 상으로는 n-1으로 접근해야 하는 것이 포인트!
코드 단순화
def solution(array, commands):
answer = []
for com in commands:
answer.append(sorted(array[com[0]-1:com[1]])[com[2]-1])
return answer
새 배열을 만들고 sort로 정렬해 answer에 담는 3 줄의 코드를 한 줄로 축약했다
요즘 파이썬 한줄코드 작성에 재미를 붙여서 코드 수 줄이는 방법을 연구하고 있는데,
극한의 한줄코드를 추구한다면 가독성 면에서는 좀 떨어질 수도 있을 것 같다.
Python To Java
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int leng = commands.length;
int[] answer = new int[leng];
for(int i=0;i<leng;i++){
int[] newArr = new int[commands[i][1] - commands[i][0]+1];
System.arraycopy(array,commands[i][0]-1,newArr,0,(commands[i][1] - commands[i][0])+1);
Arrays.sort(newArr);
answer[i] = newArr[commands[i][2]-1];
}
return answer;
}
}
코드 단순화(java)
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int leng = commands.length;
int[] answer = new int[leng];
for(int i=0;i<leng;i++){
int[] newArr = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(newArr);
answer[i] = newArr[commands[i][2]-1];
}
return answer;
}
}
새로운 배열을 만들고 System.arraycopy()로 복사 하는 과정을 copyOfRange()를 사용해 한 줄로 줄일 수 있었다!
'코딩테스트 > 🐤 코드리뷰, Python to Java' 카테고리의 다른 글
[프로그래머스/level 4] 도둑질 (문제/정답/풀이) (1) | 2023.11.15 |
---|