这里的时间复杂度 O(N^2) 怎么样?
How is the time complexity O(N^2) here?
我已经知道这个问题的答案是 O(N^2)
,但我不知道如何回答。我知道for循环运行sN
次,但是怎么会运行N^2
次呢?
public static String rev(String s) {
String r = "";
int N = s.length();
for (int i = 0; i < N; i++) {
r = s.charAt(i) + r;
}
return r;
}
在Java中,String
在一个循环中串联r = s.charAt(i) + r
是O(N^2)
,因为Strings
是不可变的-[=10的新副本=] 在每次串联时创建。
我已经知道这个问题的答案是 O(N^2)
,但我不知道如何回答。我知道for循环运行sN
次,但是怎么会运行N^2
次呢?
public static String rev(String s) {
String r = "";
int N = s.length();
for (int i = 0; i < N; i++) {
r = s.charAt(i) + r;
}
return r;
}
在Java中,String
在一个循环中串联r = s.charAt(i) + r
是O(N^2)
,因为Strings
是不可变的-[=10的新副本=] 在每次串联时创建。