tags:

views:

138

answers:

6

I have two integer lists (List<int>). They contain the same elements, but List 1 contains elements that are not in the List 2.

How to find which elements of the List 1 ARE NOT in the List 2.

Thanks :)

PS. lang is c#

A: 

If they are not sorted or something, you are going to have a hard time.

Either O(N^2) algorithm (a simple, stupid loop) or additional data structures, tell me which do you prefer.

Or, you can of course alter the source data by sorting, which I suppose is not an option.

Pavel Radzivilovsky
In what way is sorting them both in O(N log N) not a possibility?
Pieter
Well you could radix-sort both lists O(kN) and compute the difference O(N).
KennyTM
+17  A: 

You can use IEnumerable.Except:

list1.Except(list2);
bruno conde
+1. You've beat me to it.
brickner
could not do this way because the argument of Except must be IEnumerable. List as an argument is unacceptable.
trnTash
@trnTash: List<T> implements IEnumerable<T>. The code is correct.
dtb
+2  A: 
new HashSet<int>(l1).ExceptWith(l2);
Matthew Flaschen
A: 

For simplicity you can use the Contains method and check for one list not containing an element of the other:

for (int i = 0; i < list2.Count; ++i)
{
    if (!list1.Contains(list2[i]) //current element is not in list 1
        //some code
}
Mike Webb
This is backwards, and an O(N^2) algorithm.
Matthew Flaschen
this could do as well but the other solution is much faster and less code
trnTash
+1  A: 

A very easy solution:

HashSet<int> theSet1 = new HashSet<int>(List1);
theSet1.ExceptWith(List2);
trnTash
HashSet helped after all. Thanks!
trnTash
You're thanking yourself for your own answer?
Ben M
No. To the guy who deleted his post.
trnTash
A: 

If your solution is that firs list contain second and to you hunting onli records added after first list , Maybe this is going to be useful

public static int DokleSuIsti(IList<string> prevzemNow, IList<string> prevzemOld)
        {
            int dobroja = 0;
            int kolikohinaje;
            if (prevzemOld.Count() < prevzemNow.Count())
            {
                kolikohinaje = prevzemOld.Count();
            }
            else
            {
                kolikohinaje = prevzemNow.Count();
            }



            for (int i = 0; i < kolikohinaje; i++)
            {
                if (!Object.Equals(prevzemNow[i], prevzemOld[i]))
                {
                    dobroja = i;
                    return dobroja;
                }
                dobroja = i;
            }
            return dobroja;
        }

After that you can use that int as starting point for walk trough your Ilist

adopilot