classSolution{public:intfindPoisonedDuration(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.思路一:模拟
classSolution{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.思路二:找规律进行优化
classSolution{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.最后一行字符elseif(i == numRows -1)for(int i_n = numRows -1; i_n < n; i_n += d) ret += s[i_n];//3.中间字符:左在右不在特殊情况elsefor(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)
classSolution{public:
string countAndSay(int n){//1.开始字符串:
string ret("1");//2.内容的遍历:while(--n){int left =0, right =0;
string s1;//3.字符串的遍历+数据更新for(left =0, right =0; right < ret.size(); right++){if(ret[right]!= ret[left]){int n =(right - left )*10+(int)(ret[left]-'0');//1.数据保存一下:
s1 +=to_string(n);//2.指针数值更新
left = right;}}//4.数据都不去走for中的if产生的问题。int n =(right - left)*10+(int)(ret[left]-'0');
s1 +=to_string(n);
ret = s1;}return ret;}};