
๋ฆฌํธ์ฝ๋ Relative Ranks Easy๋ ๋ฒจ ๋ฌธ์ ์๋ค. ๋ณดํต ๋ฆฌํธ์ฝ๋์ easy ๋์ด๋๋ ๋ฌธ์ ์์ ์ค๋ช ํ๋ ๊ทธ๋๋ ํ๋ฉด ๋ ์๊ฐ์ด๊ณผํ ์ผ๋ ๊ฑฐ์ ์์ด์ brute force ๋ฐฉ์์ผ๋ก ํ์ด๋ดค๋ค.
class Solution {
public String[] findRelativeRanks(int[] score) {
int[] sortedScore = Arrays.stream(score)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
Map<Integer, Integer> hm = new HashMap<>();
for(int i = 1; i <= sortedScore.length; i++) {
hm.put(sortedScore[i - 1], i);
}
String[] result = new String[sortedScore.length];
for(int i = 0; i < sortedScore.length; i++) {
if(hm.get(score[i]) == 1) {
result[i] = "Gold Medal";
} else if (hm.get(score[i]) == 2) {
result[i] = "Silver Medal";
} else if (hm.get(score[i]) == 3) {
result[i] = "Bronze Medal";
} else {
result[i] = String.valueOf(hm.get(score[i]));
}
}
return result;
}
}

ํ์ง๋ง ์ด๋ฒ์ฃผ์๋ ํ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ฐฐ์ ๊ธฐ ๋๋ฌธ์ ์ด ๋ฌธ์ ๋ priority queue๋ฅผ ์ฌ์ฉํด์ ํ ์ ์์๊ณ pq๋ฅผ ์ฌ์ฉํด์ ํผ ๋ต์๋ ๊ฐ์ ธ์๋ดค๋ค.
class Solution {
public String[] findRelativeRanks(int[] score) {
int n = score.length;
PriorityQueue<Pair<Integer, Integer>> maxheap =
new PriorityQueue<>((p1, p2) -> (p2.getValue() - p1.getValue()));
for (int i = 0 ; i < n ; i++) {
maxheap.add(new Pair(i, score[i]));
}
String[] ans = new String[n];
int place = 1;
while (!maxheap.isEmpty()) {
Pair<Integer, Integer> top = maxheap.poll();
int curIndex = top.getKey();
if (place == 1) {
ans[curIndex] = "Gold Medal";
} else if (place == 2) {
ans[curIndex] = "Silver Medal";
} else if (place == 3) {
ans[curIndex] = "Bronze Medal";
} else {
ans[curIndex] = String.valueOf(place);
}
place++;
}
return ans;
}
}
'์ฝ๋ฉํ ์คํธ > TIL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[99ํด๋ฝ] 19์ผ์ฐจ ๋ฌธ์ : ์ ๋๊ฐ ํ (0) | 2025.02.13 |
---|---|
[99ํด๋ฝ] 18์ผ์ฐจ ๋ฌธ์ : ํฌ๋ฆฌ์ค๋ง์ค ์ ๋ฌผ (0) | 2025.02.12 |
[99ํด๋ฝ] 16์ผ์ฐจ ๋ฌธ์ : ๋ ๋งต๊ฒ (0) | 2025.02.11 |
[99ํด๋ฝ] 15์ผ์ฐจ ๋ฌธ์ : ๊ท ํ์กํ ์ธ์ (0) | 2025.02.08 |
[99ํด๋ฝ] 14์ผ์ฐจ ๋ฌธ์ : ์๋น ๋ฉ๋ด (1) | 2025.02.06 |
๋๊ธ