Java Solution Sorting & BinarySearch (Not using extra array)


  • 0
    I
    public String[] findRelativeRanks(int[] nums) {
        String[] res = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            res[i] = String.valueOf(nums[i]);
        }
        
        Arrays.sort(nums);
        
        for (int i = 0; i < res.length; i++) {
            int n = Integer.valueOf(res[i]);
            int rank = res.length - Arrays.binarySearch(nums, n);
            if (rank == 1) {
                res[i] = "Gold Medal";
            } else if (rank == 2) {
                res[i] = "Silver Medal";
            } else if (rank == 3) {
                res[i] = "Bronze Medal";
            } else {
                res[i] = String.valueOf(rank);
            }
        }
        return res;
    }

  • 0
    L

    It's a clean solution. Thanks for sharing!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.