https://school.programmers.co.kr/learn/courses/30/lessons/152995
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
나는 주어진 점수 데이터를 기반으로 특정 인물(완호)의 순위를 계산하였다.
입력으로 주어진 2차원 배열 scores는 각 사람이 받은 두 점수를 나타낸다.
완호의 첫 번째 점수와 두 번째 점수는 n과 m에 저장된다.
각 사람의 점수와 추가 정보를 저장하기 위해 Person 객체를 사용하며,
이를 저장하는 배열 arr를 생성한다.
각 Person 객체는 scoreA(첫 번째 점수), scoreB(두 번째 점수), scoreSum(두 점수의 합), num(고유 번호), rank(순위)를 갖고 있다.
점수를 기반으로 정렬하는 첫 단계는 scoreA를 기준으로 내림차순,
동일한 경우 scoreB를 기준으로 오름차순으로 정렬한다.
이 정렬을 통해 첫 번째 점수가 높은 사람부터 순차적으로 처리하며,
두 번째 점수의 최대값을 관리한다. 만약 현재 사람의 두 번째 점수가 최대값보다 작다면 인센티브를 받을 수 없는 상태로 간주하고,
scoreA와 scoreB를 -1로 설정해 제외한다.
이때, 완호가 제외된다면 바로 -1을 반환한다.
조건 필터링이 끝난 후, 배열 arr를 scoreSum(두 점수의 합)을 기준으로 내림차순으로 재정렬한다. 정렬된 배열을 순회하면서 완호보다 총점이 높은 사람의 수를 세고,
완호가 나타난 순간 순위를 반환한다.
최종적으로 완호의 순위를 출력한다. 정렬과 필터링을 통해 문제를 해결했다.
import java.util.*;
class Solution {
class Person {
int scoreSum;
int scoreA;
int scoreB;
int num;
int rank;
public Person(int scoreA, int scoreB, int num) {
this.scoreSum = scoreA + scoreB;
this.scoreA = scoreA;
this.scoreB = scoreB;
this.num = num;
}
public void setRank(int n) {
this.rank = n;
}
}
public int solution(int[][] scores) {
int answer = 0;
int size = scores.length;
int n = scores[0][0];
int m = scores[0][1];
Person[] arr = new Person[size];
for (int i = 0; i < size; i++) {
arr[i] = new Person(scores[i][0], scores[i][1], i);
}
Arrays.sort(arr, (o1, o2) -> {
if (o1.scoreA != o2.scoreA) return o2.scoreA - o1.scoreA;
return o1.scoreB - o2.scoreB;
});
int maxScoreB = 0;
for (Person person : arr) {
if (person.scoreB < maxScoreB) {
if (person.scoreA == n && person.scoreB == m)
return -1;
person.scoreA = -1;
person.scoreB = -1;
} else {
maxScoreB = person.scoreB;
}
}
Arrays.sort(arr, (o1, o2) -> {
return (o2.scoreSum) - (o1.scoreSum);
});
answer = 1;
for (Person person : arr) {
if (person.scoreA == -1 && person.scoreB == -1) continue;
if (person.scoreSum > n + m) {
answer++;
} else if (person.scoreA == n && person.scoreB == m) {
break;
}
}
return answer;
}
}
'Algorithm & Data Structures > Programers' 카테고리의 다른 글
Lv 2. N-Queen (1) | 2025.01.03 |
---|---|
Lv 2. 과제 진행하기 (1) | 2024.12.30 |
Lv 3. 파괴되지 않은 건물 (0) | 2024.12.23 |
Lv 3. 합승 택시 요금 (1) | 2024.12.18 |
Lv 3. 자물쇠와 열쇠 (0) | 2024.12.16 |