Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

algorithm - Is this method BigO(n^2) or BigO(nLog(n))?

This is a method i wrote that checks if two strings are premutations of each other:

public static boolean permutation(String str1, String str2) {

boolean terminate = false;

for(int x = 0; x < str1.length(); x++){
    for(int y = 0; y < str2.length(); y++){
        if(y != str2.length() - 1){
            if(str1.charAt(x) == str2.charAt(y)){
                str1.replace(String.valueOf(str1.charAt(x)), "");
                str2.replace(String.valueOf(str2.charAt(y)), "");
                break;
            }
            
        }else{
            if(str1.charAt(x) != str2.charAt(y)){
                return false;
            }else{
                str1.replace(String.valueOf(str1.charAt(x)), "");
                str2.replace(String.valueOf(str2.charAt(y)), "");
            }
            
        }
        
    }
    
}

return true;

}

as you see in the code I'm using a for loop inside another for loop but not checking all the elements of x with y (but sometimes checking all the elements of y with the current value of x), So I'm guessing is BigO(nLog(n)) since we are not comparing all the elements overall but my mind is telling me this might be BigO(n^2). Also I am removing the indexes once a certain condition is met so the other remained indexes Won't inspect the removing elements, in my opinion it is a BigO(nLog(n)) but just in case it is not i want to know why.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You haven't considered the time complexity for the replace() method. It takes O(N) time complexity.

Agreed that you are processing the strings depending upon certain conditions, but the 2 for loops anyway make the time complexity O(N^2).

Therefore, overall time complexity = O(N^2 * N) = O(N^3).

To be precise, if the length of str1 is N and the length of str2 is M, then the time complexity ~ O (N * M * (N + M)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...