class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int time = 0;
for(int i=1;i<timeSeries.size();i++)
{
int time_grep = timeSeries[i] - timeSeries[i-1];
//1.时间超过
if(time_grep >= duration)
{
time += duration;
}
//2.时间没有超过
else
{
time += time_grep;
}
}
//3.最后一次攻击一定会走完!
time += duration;
return time;
}
};
三.N字型变换
1.思路一:模拟
cpp复制代码
class Solution {
public:
string convert(string& s, int numRows) {
//0.只有一行
if (numRows == 1)
return s;
//1.构建二维数组
vector<string> vv(numRows);
//2.字符排放
int flag = 1;
int a = 0;
int b = numRows - 2;
for (int i = 0; i < s.size(); i++)
{
//2-1:从上往下
if (flag == 1)
{
if (a <= numRows - 1)
{
vv[a] += s[i];
a++;
}
if (a == numRows)
{
if(numRows >= 3)
a = 0, flag = -1;
a = 0;
}
}
//2-2:从下往上
else
{
if (b >= 0)
{
vv[b] += s[i];
b--;
}
if (b == 0)
b = numRows-2, flag = 1;
}
}
//3.定义字符串类型进行+=
string ret;
for (int i = 0; i < numRows; i++) ret += vv[i];
return ret;
}
};
2.思路二:找规律进行优化
cpp复制代码
class Solution{
public:
string convert(string s, int numRows) {
//0.特殊情况判断:
if (numRows == 1)
return s;
//1.计算公差
int d = (2 * numRows) - 2;
int n = s.size();
//2.规律去模拟不需要创建额外的空间:
string ret;
for (int i = 0; i < numRows; i++)
{
//1.第一行字符
if (i == 0)
for (int i_1 = 0; i_1 < n; i_1 += d) ret += s[i_1];
//2.最后一行字符
else if (i == numRows - 1)
for (int i_n = numRows - 1; i_n < n; i_n += d) ret += s[i_n];
//3.中间字符:左在右不在特殊情况
else
for (int i_k_left = i, i_k_right = d - i; (i_k_left < n) || (i_k_right < n); i_k_left += d, i_k_right += d)
{
if(i_k_left < n )
ret += s[i_k_left];
if(i_k_right < n)
ret += s[i_k_right];
}
}
return ret;
}
};
//时间复杂度:O(n)
//空间复杂度:O(1)