VB.NET Array Intersection

后端 未结 4 938
无人及你
无人及你 2021-01-07 00:31

This could be terribly trivial, but I\'m having trouble finding an answer that executes in less than n^2 time. Let\'s say I have two string arrays and I want to know which s

4条回答
  •  庸人自扰
    2021-01-07 01:20

    Sort both lists. Then you can know with certainty that if the next entry in list A is 'cobble' and the next entry in list B is 'definite', then 'cobble' is not in list B. Simply advance the pointer/counter on whichever list has the lower ranked result and ascend the rankings.

    For example:

    List 1: D,B,M,A,I
    List 2: I,A,P,N,D,G

    sorted:

    List 1: A,B,D,I,M
    List 2: A,D,G,I,N,P

    A vs A --> match, store A, advance both
    B vs D --> B D vs D --> match, store D, advance both
    I vs G --> I>G, advance 2
    I vs I --> match, store I, advance both
    M vs N --> M List 1 has no more items, quit.
    List of matches is A,D,I

    2 list sorts O(n log(n)), plus O(n) comparisons makes this O(n(log(n) + 1)).

提交回复
热议问题