简体   繁体   中英

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.

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

and the function should return

{"b"}

These 2 arrays are to be sorted, but not the same size. 这2个数组可以排序,但大小不相同。 I just need this function to be fast.

Here's an O(n) algorithm:

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. Same for 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 .]

@Oli Charlesworth

if arr1[]={"a","b","c"} and 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).....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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