常规解法,空间复杂度时间复杂度O(n)
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
string res(s);
int n = s.size();
for(int i = 0;i < n;i++)
{
res[indices[i]] = s[i];
}
return res;
}
};
运行结果:
Runtime: 8 ms, faster than 98.74% of C++ online submissions for Shuffle String.
Memory Usage: 15.5 MB, less than 20.67% of C++ online submissions for Shuffle String.
空间复杂度O(1) 时间复杂度O(n)解法:
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
int n = s.size();
for(int i = 0;i < n;i++)
{
while(indices[i] != i)
{
swap(s[i],s[indices[i]]);
swap(indices[i],indices[indices[i]]);
}
}
return s;
}
};
运行结果:
Runtime: 16 ms, faster than 66.25% of C++ online submissions for Shuffle String.
Memory Usage: 15.4 MB, less than 43.20% of C++ online submissions for Shuffle String.