[removed] efficiently compare two integer arrays

后端 未结 6 1271
庸人自扰
庸人自扰 2020-12-30 03:14

I have two integer arrays which contain numeric values. I want to look through both lists and check for commonality (or lack of) between the lists. I.e. I want to iterate th

6条回答
  •  礼貌的吻别
    2020-12-30 03:43

    Sort them first and duck-waddle through them in parallel.

    a.sort();
    b.sort();
    
    left = []; both = []; right = []; 
    i = 0; j = 0;
    while (i < a.length && j < b.length) {
        if (a[i] < b[j]) {
            left.push(a[i]);
            ++i;
        } else if (b[j] < a[i]) {
            right.push(b[j]);
            ++j;
        } else {
            both.push(a[i]);
            ++i; ++j;
        }
    }
    while (i < a.length) {
        left.push(a[i]);
        ++i;
    }
    while (j < b.length) {
        right.push(b[j]);
        ++j;
    }
    

提交回复
热议问题