|
| 1 | +/** |
| 2 | + * [2418] Sort the People |
| 3 | + * |
| 4 | + * You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. |
| 5 | + * For each index i, names[i] and heights[i] denote the name and height of the i^th person. |
| 6 | + * Return names sorted in descending order by the people's heights. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: names = ["Mary","John","Emma"], heights = [180,165,170] |
| 11 | + * Output: ["Mary","Emma","John"] |
| 12 | + * Explanation: Mary is the tallest, followed by Emma and John. |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * Input: names = ["Alice","Bob","Bob"], heights = [155,185,150] |
| 17 | + * Output: ["Bob","Alice","Bob"] |
| 18 | + * Explanation: The first Bob is the tallest, followed by Alice and the second Bob. |
| 19 | + * |
| 20 | + * |
| 21 | + * Constraints: |
| 22 | + * |
| 23 | + * n == names.length == heights.length |
| 24 | + * 1 <= n <= 10^3 |
| 25 | + * 1 <= names[i].length <= 20 |
| 26 | + * 1 <= heights[i] <= 10^5 |
| 27 | + * names[i] consists of lower and upper case English letters. |
| 28 | + * All the values of heights are distinct. |
| 29 | + * |
| 30 | + */ |
| 31 | +pub struct Solution {} |
| 32 | + |
| 33 | +// problem: https://leetcode.com/problems/sort-the-people/ |
| 34 | +// discuss: https://leetcode.com/problems/sort-the-people/discuss/?currentPage=1&orderBy=most_votes&query= |
| 35 | + |
| 36 | +// submission codes start here |
| 37 | + |
| 38 | +impl Solution { |
| 39 | + pub fn sort_people(names: Vec<String>, heights: Vec<i32>) -> Vec<String> { |
| 40 | + let mut order = Vec::from_iter(0..names.len()); |
| 41 | + let mut names = names; |
| 42 | + order.sort_unstable_by_key(|i| std::cmp::Reverse(heights[*i])); |
| 43 | + order |
| 44 | + .into_iter() |
| 45 | + .map(|i| std::mem::take(&mut names[i])) |
| 46 | + .collect() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// submission codes end |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn test_2418_example_1() { |
| 58 | + let names = vec_string!["Mary", "John", "Emma"]; |
| 59 | + let heights = vec![180, 165, 170]; |
| 60 | + |
| 61 | + let result = vec_string!["Mary", "Emma", "John"]; |
| 62 | + |
| 63 | + assert_eq!(Solution::sort_people(names, heights), result); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_2418_example_2() { |
| 68 | + let names = vec_string!["Alice", "Bob", "Bob"]; |
| 69 | + let heights = vec![155, 185, 150]; |
| 70 | + |
| 71 | + let result = vec_string!["Bob", "Alice", "Bob"]; |
| 72 | + |
| 73 | + assert_eq!(Solution::sort_people(names, heights), result); |
| 74 | + } |
| 75 | +} |
0 commit comments