How to find reverse order pairs in two arrays?

This is a question. There are two arrays A1and A2. Find pairs of numbers in A2that were in reverse order in A1. For example, A1 = [2 6 5 8 1 3], A2 = [1 2 3 4 5 6]. Answer: (1, 2), (1, 5), (1, 6), (5, 6), (3, 5), (3, 6).

O (N ^ 2) algorithm is trivial. Is there a better algorithm? What do you think?

+3
source share
3 answers

If you have a pattern like A1 = 1111122222and A2 = 2222211111, you will output pairs (N / 2) 4 . Therefore, you cannot do better than O (N 4 ) in the worst case.

O (N 4), , . , O (N 4), O (N 2) , -sort.

index = {} # dictionary of lists defaulting to []
for i in 0..len(A2):
  index[A2[i]].append(i)
for i1 in 0..len(A1):
  for j1 in i+1..len(A1):
    for i2 in index[A1[i1]]:
      for j2 in index[A1[j1]]:
        if i2 != j2 and i1 < j1 != i2 < j2:
          print A1[i1], A1[j1]

, (1, 2) * 7, 7 , . , [(2, 1), (6, 2), (5, 3), (8, 4), (1, 5), (3, 6)] . : , , . , , , . O (NlogN).

+4

, A1 A2 ( ), Merge Sort , A1.

http://geeksforgeeks.org/?p=3968

+2

I think this algorithm is pretty close to the best. If we abandon the computational cost of constructing a trie (n ^ 2 assignement), we are left with the cost of n (n-1) / 2 operations. Somehow he uses trie to make the pair check constant. If necessary, you can, due to len (a) + len (b), scan two arrays and conclude that MAX:

#include "stdio.h"
#include "stdlib.h"

#define MAX 9
#define AEL 6
#define BEL 6

int main(){
    int b[BEL] = {2,6,5,8,1,3};
    int a[AEL] = {1,2,3,4,5,6};
    int **trie = calloc(MAX,sizeof(int*));
    int i,j;

    for(i = 0; i < MAX; i++){
        trie[i] = calloc(MAX,sizeof(int));
    }

    for(i = 0; i < AEL; i++){
        for(j = i+1; j < AEL; j++){
            trie[a[i]][a[j]] = 1;
        }
    }

    for(i = 0; i < BEL; i++ ){
        for(j = i+1; j < BEL ; j++){
            if(trie[b[j]][b[i]]){
                printf("(%d %d) ",b[j],b[i]);
            }
        }
    }

    return 0;
}
+1
source

Source: https://habr.com/ru/post/1784043/


All Articles