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

标签 c arrays

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

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/

相关文章:

asp.net-mvc - Asp.Net MVC 中数据库中的图像

javascript - ngTagsInput 3.2.0 使用 PHP 插入数组

javascript - 读取文本文件的一部分,并将值以 ","分隔插入到数组中

Rosetta Stone 上的 C 快速中值滤波器(C I/O 和图像)

c - (char*)malloc(sizeof(char)) 导致段错误,怎么办?

c++ - 使用 Objective C 类实例调用 C 函数

javascript - 使用过滤功能从另一个对象创建对象

c - Malloc 初始化空指针

c - 如何从二进制文件中读取纯文本?

c++ - 如果传递给函数,则确定数组的大小