继续解昨天的题目:https://leetcode-cn.com/problems/shortest-distance-to-a-character/submissions/
早上过来重新review代码,发现其实自己思路没有问题,超时是因为while条件死循环了,非常低级的错误。
贴下通过的代码,但是从时间消耗上来说,还是没有题解更优:
class Solution {
public int[] shortestToChar(String s, char c) {
int[] ch1 = new int[s.length()];
int tail = 0;
// 第一次遍历,把c的下标取出
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) == c) {
ch1[tail] = i;
tail++;
}
}
int[] ans = new int[s.length()];
int head = 0;
// 第二次遍历,找到最近的c算出距离,如果不是最近的就取下一个c
for (int k=0; k<s.length(); k++) {
if (ch1[head+1] !=0) {
if (Math.abs(k-ch1[head]) > Math.abs(k-ch1[head+1])) {
head++;
}
}
ans[k] = Math.abs(k-ch1[head]);
}
return ans;
}
}
网友评论