1. string 倒序,非字母位置不变;Solution: two pointer
class Solution {
public:
string reverseOnlyLetters(string S) {
int i=0;
int j=S.length();
while(i<=j){
if(!isalpha(S[i])) i++;
if(!isalpha(S[j])) j--;
else if(isalpha(S[i]) && isalpha(S[j])){
swap(S[i],S[j]);
i++;
j--;
}
}
return S;
}
};
2. Maximum Sum Circular Subarray 最大循环子序列: 前面讲过一维的最大子序列,最小子序列这个类似。dp
提示: currentmax globalmax
So there are two case.
- The first is that the subarray take only a middle part, and we know how to find the max subarray sum.
- The second is that the subarray take a part of head array and a part of tail array.
We can transfer this case to the first one.
The maximum result equals to the total sum minus the minimum subarray sum.
int maxSubarraySumCircular(vector<int>& A) {
int total = 0, maxSum = -30000, curMax = 0, minSum = 30000, curMin = 0;
for (int a : A) {
curMax = max(curMax + a, a);
maxSum = max(maxSum, curMax);
curMin = min(curMin + a, a);
minSum = min(minSum, curMin);
total += a;
}
return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;
}
3. CBT树的插入操作:
本题要求插入时,返回父节点。因此需要维护一个存储有父节点的数据结构,queue是很好用的,当左右子树都存在时,执行pop操作,并存入左右子树。当有一个不存在时,结束循环。由于省略的代码里面,root的存储方式本就是CBT(完全二叉树),因此只需要在新的构造函数内部添加后面函数比如insert需要用到的数据结构(维护父节点的queue)。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class CBTInserter {
public:
TreeNode* rt;
queue<TreeNode*> q;
CBTInserter(TreeNode* root) {
//相当于树的复制
rt = root;
//维护一个queue,存储当前父节点
q.push(root);
while(true){
root = q.front();
// 左右字数有一个不存在结束循环,queue的第一个数为父节点
if(root->left){
q.push(root->left);
}
if(root->right){//如果存在左右则queue的头节点不为父节点
q.pop();
q.push(root->right);
}
if(!root->left || !root->right){
break;
}
}
}
int insert(int v) {
TreeNode* par = q.front();
TreeNode* node = new TreeNode(v);
// 通过构造函数里面的queue存储父节点,取用
if(!par->left){
par->left = node;
}else{
par->right = node;
q.pop();
}
q.push(node);
return par->val;
}
TreeNode* get_root() {
return rt;
}
};
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter obj = new CBTInserter(root);
* int param_1 = obj.insert(v);
* TreeNode* param_2 = obj.get_root();
*/
4. 新歌与老歌
class Solution {
public:
long M = 1000000007;
int numMusicPlaylists(int N, int L, int K) {
vector<vector<long>> dp(L+1,vector<long>(N+1,0));
dp[0][0] =1;
for(int i=1;i<L+1;i++){
for(int j=1;j<=min(i,N);j++){
dp[i][j] = dp[i-1][j-1]*(N-j+1)%M;
dp[i][j] = (dp[i][j]+dp[i-1][j]*max(j-K,0))%M;
}
}
return (int)dp[L][N];
}
};