本文共 1748 字,大约阅读时间需要 5 分钟。
在n个整数中查找m出现的位置,如果出现多次,则依次输出。如果没有找到,输出Not Found。
输入包括两行:
第一行:n(0 < n ≤ 10000)和n个整数。第二行:m
输出m在n个整数中出现的位置。如果出现多次则均输出。如果没有找到,输出Not Found。
8 3 1 23 8 3 10 7 33
1 5 8
我们需要在给定的整数序列中查找特定值m的位置。如果m在序列中出现多次,则需要依次输出所有位置。如果m没有在序列中出现,则输出Not Found。
为了高效查找和记录m的位置,我们可以使用数组或栈。这里可以选择数组,因为它能够直接记录每个整数的位置。
以下是实现该功能的C代码:
#include#include int main(void) { int n, m; // 初始化一个大小为n的数组,记录每个整数的位置 char positions[n][10]; // 假设整数最大为1000 int dup_pos = -1; // 记录是否有重复 int i, j; scanf("%d", &n); // 读取n个整数 for (i = 0; i < n; ++i) { char num[10]; scanf("%d", num); if (memcmp(num, &m, 10) == 0) { // 记录每次出现的位置索引 if (positions[dup_pos] != 0) { // 上一次出现的位置是在数组中的哪一行? // 这里使用`sprintf`将索引转为字符串后拼接到`positions`数组中 char pos[5]; sprintf(pos, "%d", i); strcat(positions[dup_pos], pos); strcat(positions[dup_pos], " "); } else { // 拼接当前索引 sprintf(pos, "%d", i); strcat(positions, pos); strcat(positions, " "); } dup_pos++; } } // 输出结果 if (positions != 0) { printf("%s\n", positions); } else { printf("Not Found\n"); } return 0;}
char positions[n][10];
用于记录每个整数的位置索引。strcat
拼接结果字符串,形成多个位置索引的字符串。如果m的值范围较大,使用哈希表(如unordered_map
)可能会更高效,但对于n≤10000的情况,数组方法已经足够快。如果使用栈结构,数据会被逆序存储,最后需要倒序访问索引,增加了复杂度。因此,使用数组是最优的选择。
转载地址:http://nhhyk.baihongyu.com/