我有以下結構效率與結構
struct scoreentry_node {
struct scoreentry_node *next;
int score;
int max;
char name[1];
}
;
typedef struct scoreentry_node *score_entry;
而且我有建造我的構造函數add
:
int max(int a, int b) {
if (a > b) return a;
return b;
}
score_entry add(int in, char* n, score_entry en) {
score_entry r = malloc(sizeof(struct scoreentry_node) + strlen(n))
if (en == NULL){ r->max = in; }
else { r->max = max(in, en->max); }
r->score = in;
strcpy(r->name, n);
r->next = en;
return r;
}
我有以下的功能,通過我的結構掃描搜索名稱併產生該名稱的最高分數:
int maxiscore(score_entry a, char* name)
{
int highestscore = -1000000000;
for (a; a != NULL; a = a->next)
{
if (strcmp(a->name, name) == 0 && a->score > highestscore)
{
highestscore = a->score;
}
}
return highestscore;
}
我是w如果我可以讓我的maxiscore
函數在O(1)中運行[不需要掃描我的結構]?我正在考慮添加另一個字段到我的結構,但我必須考慮它需要根據具體的輸入名稱而有所不同。任何建議/提示?
什麼是'char name [1];'?如果你想要一個字符,爲什麼不用'char名字;'?如果你希望它是以空字符結尾的字符串,那麼只有**空終止符將適合單字符數組。 – Imp 2012-03-31 22:20:12
使其成爲O(1)的唯一方法是不斷排序列表,這會比最大分數爲O(n)更大的浪費。 – 2012-03-31 22:20:28
使其成爲O(1)的唯一方法是將列表實現爲'priorityQueue'(即排序)或將列表實現爲'HashTable'。用你當前的設置'HashTable'選項需要基本上重做整個代碼。你可以實現一個'priorityQueue'。 – twain249 2012-03-31 22:22:11