Sort By Height
Description
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180]
, the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] array.integer a
If
a[i] = -1
, then theith
position is occupied by a tree. Otherwisea[i]
is the height of a person standing in theith
position.Guaranteed constraints:
1 ≤ a.length ≤ 1000
,
-1 ≤ a[i] ≤ 1000
. -
[output] array.integer
- Sorted array
a
with all the trees untouched.
- Sorted array
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
10
function sortByHeight(a) {
var people = a.filter((el) => el != -1);
people.sort((a, b) => b - a);
for (var i = 0; i < a.length; i++) {
if (a[i] !== -1) {
a[i] = people.pop();
}
}
return a;
}