gpt4 book ai didi

c - 在多个数组中执行多重搜索的最佳方法

转载 作者:行者123 更新时间:2023-11-30 20:41:27 26 4
gpt4 key购买 nike

考虑下表,其中(目的地,路线)映射到节点

Destination_id(a)   route_id(b)   next_node(c)
4 1 6
7 1 9
7 2 8
8 4 4
7 3 2

示例:

Given input (Destination_id, route_id) : (7,3)
Expected output : 2

Given input (Destination_id, route_id) : (4,1)
Expected output : 2

换句话说,表中的有效映射将是:

Input    Ouput
(4, 1) -> 6
(7, 1) -> 9
(7, 2) -> 8
(8, 4) -> 4
(7, 3) -> 2

我已经编写了代码,并且得到了完美的输出。有没有其他有效的方法来实现这个?

#include<stdio.h>


int main()
{
int i,store;
int a[5]={4,7,7,8,7};
int b[5]={1,1,2,4,3};/// this will be always unique with respect to the search element of 'a' for eg.<7,1>, <7,2>
int c[5]={6,9,8,4,2};
int found_indices[5]; // array used to store indices of found entries..
int count = 0; //n entries found;
int ele_a, ele_b;
printf("Enter the element to be search in array a\n");
scanf("%d",&ele_a);
printf("Enter the element to be search in array b\n");
scanf("%d",&ele_b);
// searching for the element
for (i=0; i<5; i++)
{
if (a[i]==ele_a)
{
found_indices[count ++] = i; // storing the index of found entry

}
}
if (count!=0) {
for (i=0; i<count; i++)
{
if (b[found_indices[i]]==ele_b)
{
store=found_indices[i];

}
}
}
printf("Element found %d ", c[store]);
}

最佳答案

试试这个:

for (i = 0; i < 5; i++) {
if (a[i] == ele_a && ele_b == b[i]) {
printf("Element found %d ", c[i]);
break;
}
}

如果映射表很大,那么哈希表就是最佳选择。

关于c - 在多个数组中执行多重搜索的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com