LeetCode-10
2020-07-25
Z 字形变换
AC代码
1 | class Solution { |
优化思路
两层while循环多次判断p<n,效率底下,实际上只需要当t_numRows==0或t_numRows==numRows-1时改变方向即可
实际上需要的string数组长度是min(n, numRows)
优化代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1) {
return s;
}
int n = int(s.size());
int len = min(numRows, n);
vector<string> temp(len);
int t_numRows = 0;
bool goingDown = false;
for(int i = 0; i < n; i++) {
temp[t_numRows] += s[i];
if (t_numRows == 0 || t_numRows == numRows-1) {
goingDown = !goingDown;
}
t_numRows += goingDown ? 1 :-1;
}
string res;
for (int i = 0; i < len; i++) res += temp[i];
return res;
}
};再次优化
可以直接找新旧数列的数字关系,直接计算
优化代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1) {
return s;
}
int len_s = int(s.size());
int unit =(2*numRows-2);
int n = len_s/unit;
int remain = len_s%unit;
string res(len_s, 0);
for (int i = 0; i < len_s; i++) {
int p = 0;
if (i%unit == 0) {
p = i/unit+1;
} else {
int r = i%unit + 1,c = i/unit+1;
if (r > numRows) {
r = unit-r+2;
p = 1;
} else if (r == numRows) {
p = 1-c;
}
p += n + (n*2)*(r-2) + 2*(c-1) + min(r-1, remain)+1;
if (remain > numRows) {
p += max(r-(unit-remain+2),0);
}
}
res[p-1] = s[i];
}
return res;
}
};最终成绩
执行用时:8 ms, 在所有 C++ 提交中击败了98.89%的用户
内存消耗:7.7 MB, 在所有 C++ 提交中击败了100.00%的用户