|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
4 | 4 |
|
| 5 | +- great, this seems easy. I know there's a concise syntax for sorting one list by another in Python; let's see if I can remember it... |
| 6 | +- I very much doubt we'll be able to beat Python's built-in sorting algorithm with some creative approach here, since [`powersort`](https://docs.python.org/release/3.11.0/whatsnew/changelog.html#id100:~:text=bpo%2D34561%3A%20List,strategy%20did%20better.) is $O(n \log n)$, implemented in C, and heavily optimized |
| 7 | + |
5 | 8 | ## Refining the problem, round 2 thoughts
|
6 | 9 |
|
7 | 10 | ## Attempted solution(s)
|
| 11 | + |
| 12 | +```python |
| 13 | +class Solution: |
| 14 | + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: |
| 15 | + return [name for _, name in sorted(zip(heights, names), reverse=True)] |
| 16 | +``` |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +Huh, I'm surprised that only beat ~50% of submissions. Someone must've found a faster way... let me try something real quick... |
| 21 | + |
8 | 22 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 23 | +class Solution: |
| 24 | + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: |
| 25 | + return (name for _, name in sorted(zip(heights, names), reverse=True)) |
11 | 26 | ```
|
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | +Aha -- whatever code Leetcode runs on the backend to evaluate submissions will accept a generator when the question calls for a list/array. That's a cheesy but kinda neat trick to remember for the future. Let's try one more thing just for curiosity's sake: |
| 32 | + |
| 33 | +```python |
| 34 | +class Solution: |
| 35 | + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: |
| 36 | + for _, name in sorted(zip(heights, names), reverse=True): |
| 37 | + yield name |
| 38 | +``` |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +Cool, that's what I kinda expected would happen -- better memory performance since we now aren't even constructing the generator object in memory, but slightly slower runtime because the function itself is now a Python-level generator instead of a built-in/internally optimized generator expression. |
0 commit comments