java - 这个算法的大O复杂度是多少

标签 java time-complexity complexity-theory

需要找到我的解决方案的 Big O 复杂度 LeetCode problem .

我无法估计复杂性,因为当检测到重复字符时,会从队列中重复删除,如果没有重复删除,由于遍历字符串的单个 for 循环,它应该是 O(n)。

发布问题要点和我的解决方案供您引用:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

我的解决方案:

import java.util.Hashtable;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Queue<Character> q = new LinkedList<Character>();
        Hashtable<Character, Boolean> chars = new Hashtable<Character, Boolean>();
        int maxLen = 0;
        for (int i = 0; i < s.length(); i++)
        {
            char ch = s.charAt(i);
            if (!chars.containsKey(ch))
            {
                q.add(ch);
                chars.put(ch,true);
            }
            else
            {
                int len = q.size();
                System.out.println(len);
                while(q.peek()!=ch)
                {
                    chars.remove(q.remove());
                }
                q.remove();
                q.add(ch);
                if (len > maxLen)
                maxLen = len;
            }
        }
        if (q.size() > maxLen)
            return q.size();
        return maxLen;
    }
}

最佳答案

你的解决方案将是 O(n)。 for 循环中的内容并不那么重要,重要的是循环运行的次数。这是因为循环的内部部分将是一些任意数量的操作,这些操作只是一个常量。由于在大 O 中我们不关心常量,更重要的是循环运行的次数,即 N。

也许一些数学可以帮助证明:

假设 N = 5,您不知道循环将执行多少次操作,但您知道它将运行 5 次。首先假设它只做了一次操作,那么操作次数当然是5,即1*N。然后假设循环执行了 100 次操作,则操作次数为 500,即 100*N。在这两种情况下,大 O 都是 O(n)。然后,您可以假设对于任意数量的循环操作,您仍然会得到 O(n)。我不知道这个数学有多有效,但总体想法是有道理的。

关于java - 这个算法的大O复杂度是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42094468/

相关文章:

java - 将映射与 char 数组作为值进行比较 - Java

java - for 循环的运行时,其中变量依赖于外部循环

data-structures - 将非重叠范围映射到值的数据结构?

java - 将数组中的双空格替换为单空格

java - requestLegacyExternalStorage 在 Android 11 - API 30 中不起作用

c# - 为什么 HashSet<T>.IntersectWith 的时间复杂度取决于相等比较器?

java - 大O 方法的复杂性

algorithm - 复杂度是 O(log(n) + log(n/2) + log(n/4) + log(n/8) + ... + log(2)) = O(log(n)) 吗?

python - 拉普拉斯展开复杂度计算(递归)

java - Jpa 存储库查询 - java.lang.Object;不能转换到模型