Re: Arrays Intersection
- From: glen herrmannsfeldt <gah@xxxxxxxxxxxxxxxx>
- Date: Fri, 30 May 2008 05:52:03 -0800
Infinity77 wrote:
I have received so many nice answers in this newsgroup that I
thought I could ask one more question. I am trying to find the
intersection of 2 one-dimensional integer arrays, where "intersection"
means the common elements in both arrays, i.e.:
a = [1,2,3,4,5,6]
b = [5, 6, 7]
intersection(a, b) ==> [5, 6]
Did someone else ask this recently? It sounds familiar.
Sort the two lists, if they aren't already.
You need an output array at least as long as the
shortest list. (Or it can be done in place, destroying
the input data.)
Initialize two index variables, one to the beginning
of each list, and start a loop. If the two elements
are equal, add to the output list and increment both
index variables. Otherwise increment the index variable
of the lower list element. Repeat until one is past the
end of its list.
-- glen
.
- References:
- Arrays Intersection
- From: Infinity77
- Arrays Intersection
- Prev by Date: Re: Arrays Intersection
- Next by Date: Re: Arrays Intersection
- Previous by thread: Re: Arrays Intersection
- Next by thread: warning on running image !!!!!
- Index(es):
Relevant Pages
|
|