Java
2차원배열 정렬 및 중복계산제거로 인한 알고리즘 실행시간 줄이기
yougeun
2022. 10. 27. 17:08
728x90
2차원 배열 정렬
(1) Comparator 클래스 구현
Arrays.sort(scope, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0]-o2[0]; // 첫번쨰 숫자 기준 오름차순
//return o2[0]-o1[0]; // 첫번째 숫자 기준 내림차순
//return o1[1]-o2[1]; // 두번째 숫자 기준 오름차순 {
//return o2[1]-o1[1]; // 두번째 숫자 기준 내림차순
}
});
(2) 람다 사용
Arrays.sort(scope,(o1, o2) ->o1[0]-o2[0]);
(3) Comparator.comparing() 사용
Arrays.sort(scope, Comparator.comparingInt(o -> o[0]));
알고리즘 실행시간 줄이기
public int solution(int distance, int[][] scope, int[][] times) {
int answer = Integer.MAX_VALUE;
for(int i=0; i<scope.length;i++){
int scopeMin = Math.min(scope[i][0],scope[i][1]);
int scopeMax =Math.max(scope[i][0],scope[i][1]);
for(int j= scopeMin; j<=scopeMax; j++){
if(j%(times[i][0]+times[i][1])<=times[i][0] && j%(times[i][0]+times[i][1])>=1 ){
if(answer>j){
answer =j;
}
}
}
}
if(answer==Integer.MAX_VALUE){
return distance;
}
return answer;
}
public static int solution(int distance, int[][] scope, int[][] times) {
int answer = Integer.MAX_VALUE;
for(int i=0; i<scope.length;i++){
int scopeMin = Math.min(scope[i][0],scope[i][1]);
int scopeMax =Math.max(scope[i][0],scope[i][1]);
for(int j= scopeMin; j<=scopeMax; j++){
int period = times[i][0]+times[i][1];
if(j%period<=times[i][0] && j%period>=1 ){
if(answer>j){
answer =j;
}
}
}
}
if(answer==Integer.MAX_VALUE){
return distance;
}
return answer;
}
if문 안 period를 계산하는 것을 2번에서 1번으로 줄이니 데이터 개수가 많을 경우 실행시간이 줄어든 것을 볼 수 있었다.
728x90