声明大小为“常量”的数组的空间复杂度是多少?

问题描述

当您声明“ lastIndexes”数组时,它的大小将始终为“ 26”。它不会根据输入而改变。那么这是否意味着该操作是O(1)恒定空间?请忽略分区数组,我只是对“ Array(26)”操作感到好奇。

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

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;
};

解决方法

Big O用于变量变化的时间复杂度比较。由于创建数组所需的时间不依赖于变化的变量(例如,输入的大小),因此应为O(1)。

,

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

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