简体   繁体   English

maxOccuringDigit() function 的时空复杂度是多少?

[英]What is the Time and space Complexity of maxOccuringDigit() function?

static int maxOccuringDigit(int n) {
    int tempNum = n;
    if (tempNum < 0)
        tempNum = -tempNum;

    int[] count = new int[10];

    while (tempNum != 0) {
        int rem = tempNum % 10;
        count[rem] = count[rem] + 1;
        tempNum = tempNum / 10;
    }

    int maxCount = count[0];
    int digit = 0;
    for (int i = 1; i < count.length; i++) {
        if (count[i] > maxCount) {
            maxCount = count[i];
            digit = i;
        } else if (count[i] == maxCount)
            digit = -1;
    }
    return digit;
}

The task is to find which digit occurs maximum times.任务是找出哪个数字出现的次数最多。 I need help in analyzing the time complexity of this function.我需要帮助来分析这个 function 的时间复杂度。 I think it should be O(k) where k is the total digits in given number n.我认为它应该是O(k),其中 k 是给定数字 n 的总位数。 Mainly I am curious about the time complexity of for loop used here .主要是我对这里使用的 for 循环的时间复杂度感到好奇。 As it will always loop for 10 times, can we consider it as constant time operation?由于它总是循环 10 次,我们可以认为它是恒定时间操作吗?

So total O(k + 10) ~ O(k) time .所以总 O(k + 10) ~ O(k) 时间 Is that correct?那是对的吗?

Also for space complexity it is using 10 extra spaces of array only, so what will be its space complexity too?同样对于空间复杂度,它仅使用 10 个额外的数组空间,那么它的空间复杂度也将是多少?

The while loop will run log10(N) times. while 循环将运行log10(N)次。 Yes, the for loop is run once for N and the fact that it runs 10 times is negligible, ie C = 10.是的,for 循环为 N 运行一次,它运行 10 次的事实可以忽略不计,即 C = 10。

So the runtime complexity of your method is log10(N) + C and as C is negligible, log10(N) is its runtime complexity.所以你的方法的运行时复杂度是log10(N) + C并且因为 C 可以忽略不计, log10(N)是它的运行时复杂度。

Space complexity is O(1) .空间复杂度为O(1)

The first loop depends on the number of digits, k , and is O(k) .第一个循环取决于位数k ,并且是O(k) The second loop depends on the number of elements in the count array, which is 10. Since that's a constant, it runs in O(1) .第二个循环取决于count数组中的元素数,即 10。因为这是一个常数,所以它在O(1)中运行。 The overall time complexity is therefore O(k) .因此,整体时间复杂度为O(k)

Space complexity is O(1) for the same reason as why the time complexity for the second loop is O(1) .空间复杂度为O(1)的原因与第二个循环的时间复杂度为O(1) (1) 的原因相同。

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

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