简体   繁体   English

该算法的时间复杂度:是O(n ^ 2)还是O(n)

[英]Time Complexity of this Algorithm: is it O(n^2) or O(n)

I am trying to solve "Reverse Words in a String III" of Leetcode. 我正在尝试解决Leetcode的“字符串III中的反向单词”。 I come up with a solution but I think that my time complexity is O(n^2). 我提出了一个解决方案,但我认为我的时间复杂度是O(n ^ 2)。 My code is able to pass all the test cases. 我的代码能够通过所有测试用例。 My code is as follows: 我的代码如下:

class Solution {
    public String reverseWords(String s) {
        if(s.isEmpty())
            return "";

        StringBuilder result = new StringBuilder();        
        String[] str = s.split("\\s+");
        for(String s1:str){
            char[] c1  = reverseChar(s1);
            result.append(c1).append(" ");
            }
        return result.toString().trim();
    }

    public char[] reverseChar(String s){
        char[] c = s.toCharArray();
        int i = 0;
        int j = c.length-1;

        while(i<j){
                char temp = c[i];
                c[i] = c[j];
                c[j] = temp;
                j--;
                i++;
            }
        return c;
    }

}

O(n) ... and actually slightly less when the String length is short due to start up / tear down costs of the JVM. O(n)...,并且由于JVM的启动/拆卸成本而导致String长度较短时,实际上略小。

If you're interested in knowing precisely, I recommend researching the Java Micro-benchmarking Harness (JMH) (re: https://www.oracle.com/technetwork/articles/java/architect-benchmarking-2266277.html ). 如果您有兴趣精确了解,建议您研究Java Micro-benchmarking Harness(JMH)(re: https : //www.oracle.com/technetwork/articles/java/architect-benchmarking-2266277.html )。

I do not recommend the following poor-man's benchmark; 我不推荐以下穷人基准。 however, it answers the question all the same. 但是,它同样回答了这个问题。

    public static void main (String[] args) {
        Random r = new Random();
        char[] chars = new char[100_000]; // change this value to other benchmarks
                for (char c : chars) {
            c = (char) (r.nextInt(90) + 32);
        }

        Solution s = new Solution();
        long x1  = System.currentTimeMillis();
        s.reverseWords(Arrays.toString(chars));
        long x2 = System.currentTimeMillis();

        System.out.println("duration = " + (x2 - x1));
    }

I think the complexity is O(n/2). 我认为复杂度为O(n / 2)。 The code can be abstract as 该代码可以是抽象的

for(int i =0 ,i< str.length, i++){
    for(int j = 0,j < str[i].length/2, j++)
    {
       ...
    }
}

Say str is ['abc','abc','abc','abc'] ,the complexity is 4*(3/2) = (4*3)/2 .And 4*3 == n ,So it is O(n/2) 假设str为['abc','abc','abc','abc'] ,复杂度为4*(3/2) = (4*3)/2 ,而4*3 == n ,因此是O(n / 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM