Skip to content

Commit fa30e45

Browse files
solves #2418: Sort the People in java
1 parent 6d80d72 commit fa30e45

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -768,7 +768,7 @@
768768
| 2404 | [Most Frequent Even Element](https://leetcode.com/problems/most-frequent-even-element) | [![Java](assets/java.png)](src/MostFrequentEvenElement.java) | |
769769
| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together) | [![Java](assets/java.png)](src/CountDaysSpentTogether.java) | |
770770
| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple) | [![Java](assets/java.png)](src/SmallestEvenMultiple.java) | |
771-
| 2418 | [Sort the People](https://leetcode.com/problems/sort-the-people) | | |
771+
| 2418 | [Sort the People](https://leetcode.com/problems/sort-the-people) | [![Java](assets/java.png)](src/SortThePeople.java) | |
772772
| 2423 | [Remove Letter To Equalize Frequency](https://leetcode.com/problems/remove-letter-to-equalize-frequency) | | |
773773
| 2427 | [Number of Common Factors](https://leetcode.com/problems/number-of-common-factors) | | |
774774
| 2432 | [The Employee That Worked on the Longest Task](https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task) | | |

src/SortThePeople.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// https://leetcode.com/problems/sort-the-people
2+
// T: O(n + nlogn)
3+
// S: O(n)
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public class SortThePeople {
9+
private record Person(String name, int height) {}
10+
11+
public String[] sortPeople(String[] names, int[] heights) {
12+
final List<Person> people = getPeople(names, heights);
13+
people.sort((a, b) -> Integer.compare(b.height, a.height));
14+
return toNameArray(people);
15+
}
16+
17+
private String[] toNameArray(List<Person> people) {
18+
final String[] names = new String[people.size()];
19+
int k = 0;
20+
for (Person person : people) {
21+
names[k++] = person.name;
22+
}
23+
return names;
24+
}
25+
26+
private List<Person> getPeople(String[] names, int[] heights) {
27+
final List<Person> people = new ArrayList<>();
28+
for (int i = 0 ; i < names.length ; i++) {
29+
people.add(new Person(names[i], heights[i]));
30+
}
31+
return people;
32+
}
33+
}

0 commit comments

Comments
 (0)