Record daily LeetCode 2418. Sort Java implementation by height

Title description:

You are given an array names of strings, and an array heights of positive integers that are different from each other. Both arrays have length n.

For each subscript i, names[i] and heights[i] represent the name and height of the ith person.

Please return the corresponding name array names in descending order of height.

Initial code:

class Solution {
    public String[] sortPeople(String[] names, int[] heights) {

    }
}

Example 1:

Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Explanation: Mary is tallest, followed by Emma and John.

Example 2:

Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: first Bob is the highest, then Alice and Second Bob.

Reference answer:

class Solution {
    public String[] sortPeople(String[] names, int[] heights) {
        // 创建哈希map去存储身高与名称
        int n = names.length;
        Map<Integer,String> map = new HashMap<>();
        for(int i = 0; i < n; ++i){
            map.put(heights[i],names[i]);
        }
        // 将身高进行排序 再与map的值进行对比
        Arrays.sort(heights);
        int j = 0;
        for(int i = n - 1; i >= 0; --i){
            names[j++] = map.get(heights[i]);
        }
        return names;
    }
}

Guess you like

Origin blog.csdn.net/m0_65563175/article/details/130363180