水
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> ans(2*n);
for(int i=0; i<n; i++){
ans[2*i]=nums[i];
ans[2*i+1] = nums[i+n];
}
return ans;
}
};
排序,貌似被我写复杂了
class Solution {
public:
vector<int> getStrongest(vector<int>& arr, int k) {
sort(arr.begin(), arr.end());
int n = arr.size();
vector<int> ans(k);
vector<pair<int, int>> temp;
int mid = arr[(n-1)>>1];
for(int i=0; i<n; i++){
temp.push_back(make_pair(abs(arr[i]-mid),arr[i]));
}
sort(temp.begin(), temp.end(), [](pair<int, int>& a, pair<int, int>& b){
return a.first==b.first? a.second<b.second:a.first<b.first;
});
for(int i=0; i<k; i++){
ans[i] = temp[n-i-1].second;
}
return ans;
}
};
没啥好说的,数组加上两个记录长度和位置的值就行
class BrowserHistory {
public:
int cur;
int len;
vector<string> history;
BrowserHistory(string homepage) {
cur=0;
len=1;
history.resize(5005);
history[0]=homepage;
}
void visit(string url) {
cur+=1;
history[cur]=url;
len = cur+1;
}
string back(int steps) {
cur = max(0, cur-steps);
return history[cur];
}
string forward(int steps) {
cur = min(cur+steps, len-1);
return history[cur];
}
};
dp, 设dp[i][j][k] 为第i间房子涂第j种颜色,且组成K块的最小代价
注意边界值就好,复杂度O(m^2 n^2). 代码写的很丑
#define MAX 0x3f3f3f3f
class Solution {
public:
int minCost(vector<int>& house, vector<vector<int>>& cost, int M, int n, int target) {
// dp[i][j][k] 代表 i间房子刷成了k种连续的颜色,而且第i间房子是第j种颜色
int dp[105][105][100];
memset(dp, 0x3f, sizeof dp);
for(int i=0; i<M; i++){
if(i==0){
if(house[i]!=0)
dp[i][house[i]-1][1]=0;
else{
for(int j=0; j<n; j++)
dp[i][j][1]=min(dp[i][j][1],cost[i][j]);
}
continue;
}
for(int j=0; j<n; j++){
for(int k=1; k<=target; k++){
if(house[i]!=0){
for(int m=0; m<n; m++){
if(dp[i-1][m][k]!=MAX){
if(m==house[i]-1)
dp[i][m][k]=min(dp[i][m][k],dp[i-1][m][k]);
else
dp[i][house[i]-1][k+1]=min(dp[i][house[i]-1][k+1],dp[i-1][m][k]);
}
}
}
else{
for(int m=0; m<n; m++){
if(dp[i-1][j][k]!=MAX){
if(j==m)
dp[i][m][k]=min(dp[i][m][k],dp[i-1][m][k]+cost[i][m]);
else
dp[i][m][k+1]=min(dp[i][m][k+1],dp[i-1][j][k]+cost[i][m]);
}
}
}
}
}
}
int ans = MAX;
for(int j=0; j<n; j++){
ans = min(dp[M-1][j][target],ans);
}
return ans==MAX?-1:ans;
}
};