简体   繁体   English

C库查找两个数组之间的差异

[英]C Library Find Difference Between Two Arrays

Given 2 arrays I need a C Function/Library that will find what's different between 2 arrays. 给定2个数组,我需要一个C函数/库来查找2个数组之间的区别。

array1[] ={"a","b","c","e"}
array2[] ={"a","c","e"}

and the function should return 函数应该返回

{"b"}

These 2 arrays are guaranteed to be sorted, but not the same size. 保证这2个数组可以排序,但大小不相同。 I just need this function to be fast. 我只需要此功能快速即可。

Here's an O(n) algorithm: 这是一个O(n)算法:

Create two pointers, each initialized to point at the first element of each array. 创建两个指针,每个指针都初始化为指向每个数组的第一个元素。 Every time *p1 < *p2, add *p1 to the output array and increment p1. 每次* p1 <* p2,将* p1添加到输出数组并递增p1。 Same for p2. 与p2相同。 If they are equal, increment both. 如果它们相等,则将两者都增加。

I'll leave you to figure out how to handle duplicate elements, and what to do when one pointer reaches the end of its array. 我将让您弄清楚如何处理重复的元素,以及当一个指针到达其数组的末尾时该怎么做。

[Also, if you're able to use C++, then you should just use std::set_symmetric_difference .] [此外,如果您能够使用C ++,则应该只使用std :: set_symmetric_difference 。]

@Oli Charlesworth @奥利·查尔斯沃思

if arr1[]={"a","b","c"} and arr2[]={"d","e","f"} 如果arr1 [] = {“ a”,“ b”,“ c”}和arr2 [] = {“ d”,“ e”,“ f”}

in this case i guess ur logic will traverse elements of array(whichever is lower) but there is no need as by first comparsion only u can find the result hence result is possible for this case in o(1)..... 在这种情况下,我想您的逻辑将遍历array的元素(以较低者为准),但是没有必要,因为通过第一次比较,只有您可以找到结果,因此在o(1)的情况下可能得到结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM