๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฝ”๋”ฉํ…Œ์ŠคํŠธ/TIL

[99ํด๋Ÿฝ] 17์ผ์ฐจ ๋ฌธ์ œ: Relative Ranks

by moon101 2025. 2. 11.

 

 

 

๋ฆฌํŠธ์ฝ”๋“œ 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;
    }
}

 

 

๋ฐฐ์—ด์„ stream์„ ์‚ฌ์šฉํ•ด์„œ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ

 

 

ํ•˜์ง€๋งŒ ์ด๋ฒˆ์ฃผ์—๋Š” ํž™ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๋ฐฐ์› ๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋ฌธ์ œ๋„ 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;
    }
}

https://leetcode.com/problems/relative-ranks/solutions/5128328/beats-100-all-approaches-super-easy-clean-code-made-coding-fun/

 
 
 
 
 

๋Œ“๊ธ€