简体   繁体   English

减少时间复杂度

[英]Reducing the time complexity

The question asked is using 问的问题正在使用

struct match_score
{
char country[20];
int score;
};

wherein the structure is related to a batsman's score and the country he scored against. 其中的结构与击球手的得分及其得分所在的国家有关。 We have to find the country against which he has the highest average. 我们必须找到他的平均得分最高的国家。

I have written a code whose time complexity is O(n^2) Can anyone suggest me how to reduce the time complexity to O(nlogn) or O(n) 我已经编写了时间复杂度为O(n ^ 2)的代码,谁能建议我如何将时间复杂度降低为O(nlogn)或O(n)

Code with O(n^2) 用O(n ^ 2)进行编码

#include <stdio.h>
#include <string.h>
struct match_score
{ 
  char country[20];
  int score;
};
char *func(struct match_score *array,int len); 
main()
{
    struct match_score scores[]={
        {"Pakistan",23},
        {"India",52},
        {"Pakistan",40},
        {"India",22},
        {"Australia",80}
    };
    char *max_avg=func(scores,5);
    printf("%s",max_avg);

}
char *func(struct match_score *array,int len)
{

 int i,j,average[20],avg,l,max=0,max_num;
 char co[20];
 for(i=0;i<len;i++)
 {
     average[i]=0;
 }
 for(i=0;i<len;i++)
 {
      avg=0;
      l=0;
      strcpy(co,"");
      strcpy(co,array[i].country);
      for(j=0;j<len;j++)
      {
          if(strcmp(array[j].country,co)==0)
          {
              l++;
              avg+=array[j].score;
          } 
      }
      average[i]=avg/l;
   }

   for(i=0;i<len;i++)
   {
      if(average[i]>max)
      {
         max=average[i];
         max_num=i;
      }
   }
   for(i=0;i<len;i++)
   {
      printf("%d %d\n",i,average[i]);
   }
   return array[max_num].country;
}

The area where you hit n^2 is here; 您击中n ^ 2的区域在这里;

 for(i=0;i<len;i++)
 {
      for(j=0;j<len;j++)
      {
          if(strcmp(array[j].country,co)==0)

All this is doing is searching for duplicate countries in your array. 所有要做的就是在阵列中搜索重复的国家。 If you sort the array, at a cost of n log n, you can find duplicates in order n. 如果以n log n的代价对数组进行排序,则可以按n顺序查找重复项。 This leaves you with a new complexity of o(n log n) 这给您带来了o(n log n)的新复杂度

You could use a temporary collection in which you store the averages, then iterate over that to find the largest. 您可以使用一个临时集合来存储平均值,然后对其进行迭代以找到最大值。 This will use more space, but will be O(2n) as you have to loops in a row instead of nested. 这将占用更多空间,但将为O(2n),因为您必须连续循环而不是嵌套循环。

If you sort the arry, your complicaation reduce significanty. 如果您对进货进行分类,那么您的麻烦就会大大减少。 searching a number in a sorted arry is much quicker.... 在排序的档案中搜索数字要快得多。

Btw, you should have explained your algorithem and your code, or at least give some notes... 顺便说一句,您应该已经解释了您的算法和代码,或者至少给出了一些注释...

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

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