【问题标题】:What's the time complexity of this algorithm.Can i make it faster?这个算法的时间复杂度是多少。我可以让它更快吗?
【发布时间】:2023-03-17 15:57:01
【问题描述】:

这个算法在从 arrl 开始到 depr 结束的特定时间间隔内找到最重叠的活动(波段)。我使用快速排序来获得 O(nlogn) 时间复杂度,然后使用带有 O(n) 的 while 循环来计算数量在这些时间间隔内发生冲突的活动 1.那么这是否像 O(nlogn) + O(n) 时间复杂度? 2.我可以在 O(n) 时让它更快吗? 3.最后,理论上,是否可以使用 Timsort 来获得 O(n) 时间复杂度?

用 C 编写的代码用于 15 个活动,但假设它是泛化的并且具有未排序的 arrl 和 depr

编辑:结果是 1 小时内的活动最多

void findMaxBands(int n,int arr1[n],int depr[n]);
void quickSort(int a[],int l,int h);
int partition(int a[],int l,int h);

int main(){
    int arrl[15] = {18,18,19,19,19,19,20,20,20,20,21,22,22,22,23};
    int depr[15] = {19,21,20,21,22,23,21,22,22,23,23,23,24,24,24};
    int n = 15;
    findMaxBands(n,arrl,depr);
    return 0;
}

void findMaxBands(int n,int arrl[n],int depr[n]){
    quickSort(arrl,0,15);
    quickSort(depr,0,15);

    int guestsIn = 1,maxGuests = 1,time = arrl[0];
    int i = 1, j = 0;

    while (i < n && j < n){
        if (arrl[i] <= depr[j]){
            guestsIn++;
            if (guestsIn > maxGuests){
                maxGuests = guestsIn;
                time = arrl[i];
            }
            i++;
        }
        else{
            guestsIn--;
            j++;
        }
    }
    printf("Maximum Number of Bands : %d at time %d-%d",maxGuests,time-1,time);
}

void quickSort(int a[],int l,int h){
    int j;
    if(l<h){
        j=partition(a,l,h);
        quickSort(a,l,j-1);
        quickSort(a,j+1,h);
    }
}

int partition(int a[],int l,int h){
    int v,i,j,temp;
    v=a[l];
    i=l;
    j=h+1;

    do{
        do{
            i++;
        }while(a[i]<v&&i<=h);
        do{
            j--;
        }while(v<a[j]);
        if(i<j){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
    }while(i<j);
    a[l]=a[j];
    a[j]=v;
    return(j);
}

【问题讨论】:

  • Code Review 可能是解决此类问题的更好地方。
  • 如果您有小尺寸的离散间隔(如您的示例中所示),那么您可能还想查看散列。基本上对于每个间隔,您都会增加与该间隔重叠的所有时间点的计数器。然后您扫描时间戳并检查最大的计数器。复杂度为 O(n * I),其中 I 是区间的平均长度。
  • 确实。所有的时间间隔都必须是l=1小时才能工作。问题是我以后要根据程序写伪代码,会很复杂

标签: c algorithm sorting quicksort timsort


【解决方案1】:

1.那么这是否像 O(nlogn) + O(n) 时间复杂度?

O(n log(n)) + O(n) = O(n log(n))

参考。例如。 Big O when adding together different routines 了解更多详情。

2.我可以在 O(n) 时让它更快吗?

3.最后,理论上,是否可以使用 Timsort 来获得 O(n) 时间复杂度?

通用(比较)排序算法的最佳情况复杂度可能为 O(n),但平均/最坏情况的复杂度最多为 O(n log(n))。您可以找到几种排序算法here 及其复杂性的概述。

【讨论】:

猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多