일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- JavaScript
- react-query
- 정규표현식
- 비트연산자
- leetcode
- 디자인
- 제로베이스 프론트엔드 스쿨
- 웹접근성
- react
- wai-aria
- html&css
- 프로그래머스
- programmers
- 카드뉴스
- TypeScript
- 알고리즘
Archives
- Today
- Total
記錄
[JS]2418. Sort the People 본문

문제 링크: 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 |