506. Relative Ranks (很有趣的 Arrays.Sort)

Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]

類似要對應排名就對了

public String[] findRelativeRanks(int[] nums) {
Integer[] index = new Integer[nums.length];

for (int i = 0; i < nums.length; i++) {
index[i] = i;
}

Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));

String[] result = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
result[index[i]] = "Gold Medal";
}
else if (i == 1) {
result[index[i]] = "Silver Medal";
}
else if (i == 2) {
result[index[i]] = "Bronze Medal";
}
else {
result[index[i]] = (i + 1) + "";
}
}
return result;
}

Arrays.sort(index, (a, b) -> (nums[b] — nums[a]));這個很有趣的方法!!

另外他有一個二維的解法想法一樣

int[][] pair = new int[nums.length][2];

for (int i = 0; i < nums.length; i++) {
pair[i][0] = nums[i];
pair[i][1] = i;
}

Arrays.sort(pair, (a, b) -> (b[0] - a[0]));
總之他就是想要用下面這種感覺
Example:

nums[i] : [10, 3, 8, 9, 4]
pair[i][0] : [10, 3, 8, 9, 4]
pair[i][1] : [ 0, 1, 2, 3, 4]

After sort:
pair[i][0] : [10, 9, 8, 4, 3]
pair[i][1] : [ 0, 3, 2, 4, 1]
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.