[Solution]506. Relative Ranks

[Solution]506. Relative Ranks

·

2 min read

Problem

Problem_Link

Solutions (time, space)

O(n), O(n)

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

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

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

        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;
    }
}

Explanation

The most important code is Arrays.sort(index, (a, b) -> (nums[b] - nums[a])); This code set index array as the order of num array.

For understanding this, you need to know 3 things

  1. Array.sort() method

  2. compare() method in Interface Comparator

  3. arrow (->) operator

Array.sort(a, c)

  • a: the array to be sorted index array in this code

  • c: the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. (a, b) -> (nums[b] - nums[a]) in this code

Interface Comparater

Now, we know (a, b) -> (nums[b] - nums[a]) is Comparator.

what is Comparator?

A comparator is a comparison function, which imposes a total ordering on some collection of objects by using compare() method.

compare() method

  • 0 if the string is equal to the other string.

  • (< 0) Negative number if the string is lexicographically less than the other string

  • (> 0) Positive number if the string is lexicographically greater than the other string (more characters)

compare() method example

Integer[] arr = {10,3,8,9,4};

  • return o1 - o2; // ascending order [3,4,8,9,10]

  • return o2 - o1; // descending order [10,9,8,4,3]

  • return +1; // insertion order [10,3,8,9,4]

  • return -1; // reverse of insertion order [4,9,8,3,10]

arrow (->) operator

arrow (->) operator is a lambda expression that makes the functional interface

Conclusion

  1. arrow (->) operator to create Comparator interface

  2. This comparator interface determines the descending order

  3. use the interface and array.sort() to sort the num array as descending order

  4. Since the index array and num array index are the same(kind of bind), the index array arranged as the original position of num array

  5. change value as "Gold Medal", "Silver Medal", and "Bronze Medal"

Did you find this article valuable?

Support Eunhan's blog by becoming a sponsor. Any amount is appreciated!