Skip to content

Commit 412d024

Browse files
committed
Add solution #484
1 parent e2aeeaa commit 412d024

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@
472472
481|[Magical String](./solutions/0481-magical-string.js)|Medium|
473473
482|[License Key Formatting](./solutions/0482-license-key-formatting.js)|Easy|
474474
483|[Smallest Good Base](./solutions/0483-smallest-good-base.js)|Hard|
475+
484|[Find Permutation](./solutions/0484-find-permutation.js)|Medium|
475476
485|[Max Consecutive Ones](./solutions/0485-max-consecutive-ones.js)|Easy|
476477
486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium|
477478
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|

solutions/0484-find-permutation.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 484. Find Permutation
3+
* https://leetcode.com/problems/find-permutation/
4+
* Difficulty: Medium
5+
*
6+
* A permutation perm of n integers of all the integers in the range [1, n] can be
7+
* represented as a string s of length n - 1 where:
8+
* - s[i] == 'I' if perm[i] < perm[i + 1], and
9+
* - s[i] == 'D' if perm[i] > perm[i + 1].
10+
*
11+
* Given a string s, reconstruct the lexicographically smallest permutation perm and return it.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @return {number[]}
17+
*/
18+
var findPermutation = function(s) {
19+
const n = s.length + 1;
20+
const result = new Array(n).fill(0).map((_, i) => i + 1);
21+
22+
for (let i = 0; i < s.length; i++) {
23+
if (s[i] === 'D') {
24+
let start = i;
25+
while (i < s.length && s[i] === 'D') {
26+
i++;
27+
}
28+
let end = i;
29+
while (start < end) {
30+
[result[start], result[end]] = [result[end], result[start]];
31+
start++;
32+
end--;
33+
}
34+
i--;
35+
}
36+
}
37+
38+
return result;
39+
};

0 commit comments

Comments
 (0)