Leetcode 第30场双周赛
程序员文章站
2022-03-23 11:36:49
A.转变日期格式题目链接:https://leetcode-cn.com/problems/reformat-date/第一眼看到这题就觉得用Python做会很简单,但是我的Python实在是不太行,所以就拿C++硬怼了。C++:class Solution {public: string reformatDate(string s) { string M[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Au...
A.转变日期格式
题目链接:https://leetcode-cn.com/problems/reformat-date/
第一眼看到这题就觉得用Python做会很简单,但是我的Python实在是不太行,所以就拿C++硬怼了。
C++:
class Solution {
public:
string reformatDate(string s) {
string M[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
string MS[12] = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
string res = "";
int len = s.size();
res = res + s[len - 4] + s[len - 3] + s[len - 2] + s[len - 1] + '-';
string day = "";
int index = 0;
for(int i = 0; i < len; i++) {
if(s[i] > '9' || s[i] < '0') {
index = i;
break;
} else {
day = day + s[i];
}
}
if(day.size() == 1) {
day = '0' + day;
}
string month = "";
for(int i = index + 3; i < len; i++) {
if(s[i] == ' ') {
break;
} else {
month = month + s[i];
}
}
for(int i = 0; i < 12; i++) {
if(month == M[i]) {
month = MS[i];
break;
}
}
res = res + month + '-' + day;
return res;
}
};
之后又学习了Python的解法,真滴快啊:
class Solution:
def reformatDate(self, s: str) -> str:
d, m, y = s.split()
D = int(d[:-2])
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
M = 0
for i in range(12):
if month[i] == m:
M = i+1
Y = int(y)
res = "%04d-%02d-%02d" % (Y, M, D)
return res
B.子数组和排序后的区间和
题目链接:https://leetcode-cn.com/problems/range-sum-of-sorted-subarray-sums/
想了半天有什么优秀算法,然后发现就是暴力。。。
代码如下:
class Solution {
public:
int rangeSum(vector<int>& a, int n, int left, int right) {
vector<int> s;
for (int i = 0; i < n; ++i)
{
int tmp = 0;
for (int j = i; j < n; ++j)
{
tmp += a[j];
s.push_back(tmp);
}
}
sort(s.begin(), s.end());
int res = 0;
int MOD = 1e9 + 7;
for (int i = left-1; i < right; ++i) res = (res+s[i])%MOD;
return res;
}
};
C.三次操作后最大值与最小值的最小差
题目链接:https://leetcode-cn.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/
一次一次操作想可能性太多了,全局角度看,就是从排序后的数组两边删掉三个元素,问最后左右两端差值,那么遍历一遍就成了
代码如下:
class Solution {
public:
int minDifference(vector<int>& nums) {
int len = nums.size();
if(len <= 4) {
return 0;
}
sort(nums.begin(), nums.end());
int res = nums.back() - nums.front();
for(int i = 0; i <= 3; i++) {
res = min(res, nums[i + len - 4] - nums[i]);
}
return res;
}
};
D. 石子游戏 IV
题目链接:https://leetcode-cn.com/problems/stone-game-iv/
动态规划
代码如下:
int f[100010];
class Solution {
public:
bool winnerSquareGame(int n) {
static int flag = 0;
if (!flag)
{
flag = 1;
for (int i = 1; i <= 100000; ++i)
{
for (int j = 1; j*j <= i; ++j)
{
if (!f[i-j*j])
{
f[i] = 1;
break;
}
}
}
}
return f[n];
}
};
本文地址:https://blog.csdn.net/weixin_42396397/article/details/107312613
上一篇: VS2010安装OpenGL
下一篇: hdu2825