leetcode-484-Find Permutation
问题
By now, you are given a secret signature consisting of character ‘D’ and ‘I’. ‘D’ represents a decreasing relationship between two numbers, ‘I’ represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n (n is the length of the secret signature plus 1). For example, the secret signature “DI” can be constructed by array [2,1,3] or [3,1,2], but won’t be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can’t represent the “DI” secret signature.
On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, … n] could refer to the given secret signature in the input.
Example 1:
1 | Input: "I" |
Example 2:
1 | Input: "DI" |
Note:
The input string will only contain the character ‘D’ and ‘I’.
The length of input string is a positive integer and will not exceed 10,000
分析
思路1: 采用拓扑排序的思路,按照输入的字符串指示构建一张图,由填充值小的下标指向填充值大的下标。然后构建一个由下标升序的有限队列,每出队一个确定一个对应位置的数值,并将其子节点的入度都减1,若子节点的入度为0则加入到优先队列中。直到队列为空,则完成返回数组的赋值。时间复杂度O(nlogn),空间复杂度O(n)。
思路2: 首先将返回数组初始化为 “123..n” ,在输入字符串遇到连续的 ‘D’ 后,将返回数组中对应的部分 reverse 即可。时间复杂度O(n)。
代码1
1 | // O(nlogn) |
代码2
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/18/leetcode-484/
License: 知识共享署名-非商业性使用 4.0 国际许可协议