有人可以仔细检查我的时间复杂度/空间bigO

时间:2016-03-02 23:45:10

标签: algorithm time structure space

我必须在通过数组并检查重复项时为类编写伪代码。我希望得到一些关于我的时间复杂性和时间成本的反馈。我很确定我正确地做了大部分工作。

我唯一担心的是第三块代码是O(n ^ 3),我知道插入排序是O(n ^ 2)最坏的情况,你必须再次通过数组,这将是O( n)因此将其与O(n ^ 2)组合将导致O(n ^ 3)或否?如果不是,有人可以解释,当我知道时间成本将是O(n ^ x)x是无论数字

Alg mostFreq(file)
input: file name
output: print the word and how many times it appears

//count words
Map<string, int> map

while reading word from file 
    strip word // to lower / remove symbols/numbers
    count = map.get(word)
    if (count == null) count = 1
    freq.put(word, 1 + count)


//find max counted word 
maxCount = 0
maxCountWord = ""
for (Entry<string, int> entry: map.entrySet())
    if (entry.getValue() > maxCount0 
        maxWord = entry.getKey()
        maxCount = entry.getValue()

//print
print("Most frequent word is " + maxWord + " occurs " + maxCount + " times")

//time cost: O(n)   

-

Alg hasDuplicates(A, n)
input: A is an array of data with size n
output: if A has nay two duplicate values, return true, otherwise return false

for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
        if (j != i)
            if (A[i] == A[j]) return true

return false

//Space cost: O(n) 
//Time cost: O(n^2)

-

Alg hasDuplicates(A, n)
input: A is an array of data with size n
output: if A has nay two duplicate values, return true, otherwise return false

//insertionSort  TimeComplexity O(n^2)
for (i = 1; i < n - 1; i++)
    cur = A[i]
    j = i -1
    while (j >= 0 and A[j] > cur)
        A[j + 1] = A[j]
        j = j - 1
    A[j + 1] = cur  

//Look for duplicate
for (i = 0; i < n - 1; i++)
    if (A[i] == A[i+1]) return true

return false

//Space cost: O(n)
//Time cost: O(n^3)

-

Alg hasDuplicates(A, n)
input: A is an array of data with size n
output: if A has nay two duplicate values, return true, otherwise return false

Map<int, int> map
for (i = 0; i < n; i++)
    if (map.containsKey(A[i]) return true
    else map.put(A[i], 0)

return false

//Space cost: O(n)
//Time cost: O(n)

先谢谢你!

1 个答案:

答案 0 :(得分:0)

Alg hasDuplicates(A, n)
input: A is an array of data with size n
output: if A has nay two duplicate values, return true, otherwise return false

//insertionSort  TimeComplexity O(n^2)
for (i = 1; i < n - 1; i++)
    cur = A[i]
    j = i -1
    while (j >= 0 and A[j] > cur)
        A[j + 1] = A[j]
        j = j - 1
    A[j + 1] = cur  

//Look for duplicate
for (i = 0; i < n - 1; i++)
    if (A[i] == A[i+1]) return true

return false

//Space cost: O(n)
//Time cost: O(n^3)

它是O(n ^ 2 + n)= O(n ^ 2),你的查找循环在插入排序循环之外,它应该使用“add”而不是“multiply”。

Alg hasDuplicates(A, n)
input: A is an array of data with size n
output: if A has nay two duplicate values, return true, otherwise return false

Map<int, int> map
for (i = 0; i < n; i++)
    if (map.containsKey(A[i]) return true
    else map.put(A[i], 0)

return false

//Space cost: O(n)
//Time cost: O(n)

对于映射,我认为containsKey()put()应该是O(lg n)? 所以它是O(n lg n)而不是O(n)