我已经创建了一个程序,它计算在列表中找到string
的次数,并在屏幕上打印该数字并将其保存在int *arr
中。然而,当存在两个相同的strings
时,count
结果明显地被打印并存储在输出/列表中两次。我的问题是:我可以检查一个单词是否被发现了两次,如果是,那么free
该内存块并使用realloc()
重新分配整个int *arr
的内存吗?这是我的sortedCount()
方法,它实现了我之前所说的:
void sortedCount(int N) {
int *wordCount;
int i = 0;
wordCount = malloc(N * sizeof(int));
for(i = 0; i < N; i++) {
wordCount[i] = count(N,wordList[i],1);
}
/* free mem */
free(wordCount);
return;
}
最佳答案
假设您有一个动态分配的words
单词数组:
char **word;
size_t words;
如果您想知道唯一单词的数量,以及它们在数组中重复的次数,可以使用adisjoint-set data structure的简化版本和计数数组。
我们有两个
words
元素数组:size_t *rootword;
size_t *occurrences;
rootword
数组包含该单词第一次出现的索引,occurrences
数组包含每个单词第一次出现的次数。例如,如果
words = 5
和word = { "foo", "bar", "foo", "foo", "bar" }
,则rootword = { 0, 1, 0, 0, 1 }
和occurrences = { 3, 2, 0, 0, 0 }
。要填充
rootword
和occurrences
数组,首先将这两个数组初始化为“所有单词都是唯一的,并且只出现一次”状态: for (i = 0; i < words; i++) {
rootword[i] = i;
occurrences[i] = 1;
}
接下来,使用双循环。外部循环在唯一的单词上循环,跳过重复的单词。我们通过将其
occurrence
计数设置为零来检测重复项。内部循环是在我们不知道是否唯一的单词上,并选取当前唯一单词的副本: for (i = 0; i < words; i++) {
if (occurrences[i] < 1)
continue;
for (j = i + 1; j < words; j++)
if (occurrences[j] == 1 && strcmp(word[i], word[j]) == 0) {
/* word[j] is a duplicate of word[i]. */
occurrences[i]++;
rootword[j] = i;
occurrences[j] = 0;
}
}
在内部循环中,我们显然忽略了已知是重复的单词(并且
j
只在occurrences[j]
只能是0
或1
的单词上迭代)。这也加快了后面词根的内部循环,因为我们只比较候选词,而不是那些我们已经找到词根的词。让我们检查输入
word = { "foo", "bar", "foo", "foo", "bar" }
的循环中发生了什么。 i ╷ j ╷ rootword ╷ occurrences ╷ description
───┼───┼───────────┼─────────────┼──────────────────
│ │ 0 1 2 3 4 │ 1 1 1 1 1 │ initial values
───┼───┼───────────┼─────────────┼──────────────────
0 │ 1 │ │ │ "foo" != "bar".
0 │ 2 │ 0 │ 2 0 │ "foo" == "foo".
0 │ 3 │ 0 │ 3 0 │ "foo" == "foo".
0 │ 4 │ │ │ "foo" != "bar".
───┼───┼───────────┼─────────────┼──────────────────
1 │ 2 │ │ │ occurrences[2] == 0.
1 │ 3 │ │ │ occurrences[3] == 0.
1 │ 4 │ 1 │ 2 0 │ "bar" == "bar".
───┼───┼───────────┼─────────────┼──────────────────
2 │ │ │ │ j loop skipped, occurrences[2] == 0.
───┼───┼───────────┼─────────────┼──────────────────
3 │ │ │ │ j loop skipped, occurrences[3] == 0.
───┼───┼───────────┼─────────────┼──────────────────
4 │ │ │ │ j loop skipped, occurrences[4] == 0.
───┼───┼───────────┼─────────────┼──────────────────
│ │ 0 1 0 0 1 │ 3 2 0 0 0 │ final state after loops.
关于c - 我可以使用动态内存分配来减小int数组的大小,然后重新分配内存吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54306485/