記錄

[JS]2418. Sort the People 본문

FRONTEND STUDY/LeetCode

[JS]2418. Sort the People

prts 2022. 10. 19. 17:44

문제 링크: https://leetcode.com/problems/sort-the-people/
난이도: Easy

You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.

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

Return names sorted in descending order by the people's heights.

 

Example 1:

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

Example 2:

Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.

Constraints:

  • n == names.length == heights.length
  • 1 <= n <= 103
  • 1 <= names[i].length <= 20
  • 1 <= heights[i] <= 105
  • names[i] consists of lower and upper case English letters.
  • All the values of heights are distinct.

Related Topics: Array, Hash Table, String, Sorting


문제 풀이

 

Object를 활용해서 key에는 names[i]를, value에는 heights[i] 를 설정해주고 value 값을 기준으로 sort해주면 된다.

 

var sortPeople = function(names, heights) {
    //object=> names:heights 로 key value 만들어주고 heights기준으로 정렬 뒤 key 출력
    
    let people=[];
    for (let i=0;i<names.length;i++){
        people.push({name:names[i],heights:heights[i]});
    }
    return people.sort((a,b)=>b.heights-a.heights).map(c=>c.name);
    
    //map 활용한 더 간단한 풀이
    return names.map((c, i) => [c, heights[i]]).sort((a, b) => b[1] - a[1]).map((c) => c[0]);
};

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

120. Triangle  (0) 2022.10.24
[JS] 386. Lexicographical Numbers  (0) 2022.10.20
[JS]189. Rotate Array  (0) 2022.10.19
[JS] 34. Find First and Last Position of Element in Sorted Array  (1) 2022.10.14
[JS] 136. Single Number  (0) 2022.10.12
Comments