1507. 转变日期格式
字符串处理,呵呵,我的弟弟代码,第一题就写了十分钟
class Solution {
public:
string reformatDate(string date) {
vector<string> month = {"","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
char* p = strtok((char*)date.c_str()," ");
vector<string> v;
while(p){
v.push_back(p);
p = strtok(nullptr," ");
}
string ans = "";
ans += v[2]+"-";
int m;
for(int i=1;i<=12;i++){
if(month[i]==v[1]){
m = i;
break;
}
}
if(m<10){
ans+="0";
}
ans += to_string(m)+"-";
if(v[0][1]>='a' && v[0][1]<='z'){
ans += "0";
ans.push_back(v[0][0]);
}else{
ans.push_back(v[0][0]);
ans.push_back(v[0][1]);
}
return ans;
}
};
官方的,巧妙了的运用了stringstream输入流,题给字符串实现了分割。
class Solution {
public:
string reformatDate(string date) {
unordered_map<string, string> mp = {
{"Jan", "01"},
{"Feb", "02"},
{"Mar", "03"},
{"Apr", "04"},
{"May", "05"},
{"Jun", "06"},
{"Jul", "07"},
{"Aug", "08"},
{"Sep", "09"},
{"Oct", "10"},
{"Nov", "11"},
{"Dec", "12"}
};
stringstream ss(date);//默认以空格分隔
string year,month,day;
ss>>day>>month>>year;
day.pop_back(); //去除最后一个字符
day.pop_back();
if(day.size()==1){
day = "0"+day;
}
return year+"-"+mp[month]+"-"+day;
}
};
1508. 子数组和排序后的区间和
前缀和、暴力
时间复杂度:
class Solution {
public:
int rangeSum(vector<int>& a, int n, int left, int right) {
vector<int> s = a,res;
for(int i=1;i<n;i++){
s[i] += s[i-1];
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
int ss = s[j];
if(i>0){
ss -= s[i-1];
}
res.push_back(ss);
}
}
sort(res.begin(),res.end());
int M = (int)1e9+7 , ans = 0;
for(int i=left-1;i<=right-1;i++){
ans = (ans+res[i])%M;
}
return ans;
}
};
- k路归并解法
以nums = [3, 4, 1, 2, 5, 6] 为例 (网友的用例)
[3, 7, 8, 10, 15, 21]
[4, 5, 7, 12, 18]
[1, 3, 8, 14]
[2, 7, 13]
[5, 11]
[6]
时间复杂度:
不过在最坏情况下,仍然是
class Solution {
public:
typedef pair<int,int> P;
int rangeSum(vector<int>& nums, int n, int left, int right) {
priority_queue<P,vector<P>,greater<P>> pq;
int cnt = 0 ,ans = 0 , M = 1e9+7;
for(int i=0;i<n;i++){
pq.push(make_pair(nums[i],i));
}
while(cnt++<right){
P p = pq.top();
pq.pop();
if(cnt>=left){
ans = (ans+p.first)%M;
}
if(p.second+1<n) pq.push(make_pair(p.first+nums[p.second+1],p.second+1));
}
return ans;
}
};
class Solution {
public:
int minDifference(vector<int>& a) {
int n = a.size();
if(n<=4) return 0;
sort(a.begin(),a.end());
int ans = a[n-1]-a[0];
ans = min(ans,a[n-1]-a[3]);
ans = min(ans,a[n-2]-a[2]);
ans = min(ans,a[n-3]-a[1]);
ans = min(ans,a[n-4]-a[0]);
return ans;
}
};
1510. 石子游戏 IV
这道DP算是简单的了
class Solution {
public:
bool winnerSquareGame(int n) {
vector<int> dp(n+1);
dp[0] = 0;
for(int i=1;i<=n;i++){
for(int j = 1;j*j<=i;j++){
if(dp[i]){
break;
}
dp[i] = !dp[i-j*j] ;
}
}
return dp[n];
}
};