【问题标题】:What is the space complexity of declaring an array with a "constant" size?声明具有“恒定”大小的数组的空间复杂度是多少?
【发布时间】:2020-12-12 14:18:24
【问题描述】:

当您声明“lastIndexes”数组时,它的大小总是“26”。它不会因输入而改变。那么这是否意味着这个操作是 O(1) 常数空间?请忽略分区数组,我只是对“数组(26)”操作感到好奇。

更新:我不想知道操作的 TIME 复杂度,这将花费多少内存?

var partitionLabels = function(S) {
    const partitions = [];
    const lastIndexes = new Array(26);
    
    for(var i = 0; i < S.length; i++){
        lastIndexes[S.charCodeAt(i) - 97] = i;
    }
    
    let start = 0;
    while(start < S.length){
        let maxIndex = lastIndexes[S.charCodeAt(start) - 97];
        let curr = start;
        
        while(curr != maxIndex){
            maxIndex = Math.max(maxIndex, lastIndexes[S.charCodeAt(curr++) - 97])
        }
        
        partitions.push((curr - start) + 1);
        start = curr + 1;
    }
    
    return partitions;
};

【问题讨论】:

    标签: arrays time-complexity big-o space space-complexity


    【解决方案1】:

    Big O 用于与不断变化的变量进行时间复杂度比较。因为创建数组所需的时间不取决于变量的变化(例如输入的大小),所以它会是 O(1)。

    【讨论】:

      【解决方案2】:

      O(1) 表示恒定的空间复杂度,与输入或任何其他变量无关。

      即使您的数组大小是 100000 而不是 26,它仍然是 O(1),因为您的数组大小不依赖于任何其他值。

      【讨论】:

      • 我明白了,谢谢!这对我来说很有意义,但每次我问别人时,他们都把我搞糊涂了。
      • @Moe 您在帖子中有 2 个答案。您能否将其中一个标记为您认为最适合结束问题的解决方案。
      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多