Is the time complexity of this algorithm O(N^2)?

时间:2016-05-17 11:21:29

标签: java algorithm foreach time-complexity

Currently I'm learning about algorithm efficiency in terms of time and space complexity.
I have this algorithm written in Java:

String[] remove = value.split(",");
String[] temp = (pb.get(key)).split(",");
String newval = "";

for (int i=0;i<remove.length;i++){
    for (int j=0;j<temp.length;j++){
        if (remove[i].equals(temp[j])){
           temp[j] = "";
        }
    }
}
for (String str : temp){
    if (!(str.isEmpty())){
        newval = newval + "," + str;
    }
}
newval = newval.substring(1, newval.length());
pb.put(key, newval);

From my understanding, the first loop (nested loop) would have a time complexity of O(N^2) and the second loop would be O(N). Am I correct?
And how do I calculate for the space complexity ?

Also, an unrelated question; how do I change the first loop into an enhanced for-loop ?

Thanks in advance!

2 个答案:

答案 0 :(得分:1)

是的,时间复杂度是O(N ^ 2)因为你所说的:第一个循环的时间复杂度是O(N ^ 2)而第二个循环是O(N)(你选择最差的) (更大)一)。您仍然需要关注调用的所有方法,例如subtring(...),因为其中一个方法可能会有更大的时间复杂度,这会改变整体时间复杂度。

希望这会对你有所帮助。

答案 1 :(得分:1)

时间复杂度:O(N^2):你自己说出了答案。此外,substring()方法是Java 7中的线性时间操作。

空间复杂度:O(m+n) :当您使用两个具有大小的数组时,可以说m和n。

对于您的另一个问题,可以使用增强的for循环,如下所示

for(String str1 : remove){
 for(String str2 : temp){
   if(str1.equals(str2)){
     //
   }
 }
}