[LeetCode] Sort the People

준규·2023년 1월 3일
0

1.문제


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.


사람의 이름이 들어있는 names 와 각 사람의 키 값이 들어있는 heights 배열이 주어질 때 names 의 사람들을 키가 큰 순서대로 내림차순 정렬하여 리턴하는 문제이다.


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 <= 10^3
  • 1 <= names[i].length <= 20
  • 1 <= heights[i] <= 10^5
  • names[i] consists of lower and upper case English letters.
  • All the values of heights are distinct.

2.풀이

  1. heights 배열에서 최댓값의 index를 찾는다.
  2. names 배열에서 해당 인덱스의 사람을 찾는다.
  3. 찾은 사람을 result 배열에 넣어준다.

/**
 * @param {string[]} names
 * @param {number[]} heights
 * @return {string[]}
 */
const sortPeople = function (names, heights) {
  const result = [];
  for (let i = 0; i < heights.length; i++) {
    // 가장 키가 큰 사람의 index 구하기
    let tallestIndex = heights.indexOf(Math.max(...heights));

    // 가장 키 큰 사람의 키 값 0 으로 만들기
    heights[tallestIndex] = 0;

    // 가장 키큰 사람
    let tall = names[tallestIndex];
    // 가장 큰 순서대로 result 배열에 넣어준다.
    result.push(tall);
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글