|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Arrays; |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +public class RelativeRanks { |
| 8 | + static class Pair { |
| 9 | + private final int index; |
| 10 | + private final int value; |
| 11 | + |
| 12 | + Pair(int index, int value) { |
| 13 | + this.index = index; |
| 14 | + this.value = value; |
| 15 | + } |
| 16 | + |
| 17 | + @Override |
| 18 | + public String toString() { |
| 19 | + return "Pair{" + |
| 20 | + "index=" + index + |
| 21 | + ", value=" + value + |
| 22 | + '}'; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + private static List<Pair> getValuesWithIndex(int[] array) { |
| 27 | + List<Pair> result = new ArrayList<>(); |
| 28 | + for (int index = 0 ; index < array.length ; index++) { |
| 29 | + result.add(new Pair(index, array[index])); |
| 30 | + } |
| 31 | + return result; |
| 32 | + } |
| 33 | + |
| 34 | + private static Map<Integer, Integer> getValueToIndexMap(List<Pair> array) { |
| 35 | + Map<Integer, Integer> result = new HashMap<>(); |
| 36 | + for (int index = 0 ; index < array.size() ; index++) { |
| 37 | + result.put(array.get(index).value, index); |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + private static String getRank(int position) { |
| 43 | + switch (position) { |
| 44 | + case 1: return "Gold Medal"; |
| 45 | + case 2: return "Silver Medal"; |
| 46 | + case 3: return "Bronze Medal"; |
| 47 | + default: return position + ""; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public static String[] findRelativeRanks(int[] score) { |
| 52 | + List<Pair> sortedScores = getValuesWithIndex(score); |
| 53 | + sortedScores.sort(((o1, o2) -> Integer.compare(o2.value, o1.value))); |
| 54 | + System.out.println(sortedScores); |
| 55 | + Map<Integer, Integer> value2index = getValueToIndexMap(sortedScores); |
| 56 | + String[] result = new String[score.length]; |
| 57 | + for (int index = 0 ; index < score.length ; index++) { |
| 58 | + result[index] = getRank(value2index.get(score[index]) + 1); |
| 59 | + } |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) { |
| 64 | + System.out.println(Arrays.toString(findRelativeRanks(new int[]{10, 3, 8, 9, 4}))); |
| 65 | + } |
| 66 | +} |
0 commit comments