javascript将算法复杂度从O(n^2)做到O(n)

时间:2021-05-13 09:26:42

compare the difference of two giving array, return results: 1. elements in both array, 2. elements only in one array.

        // O(m*n + m*n) -> O(2*m*n) -> O(n^2)
function compareArr1(arr1, arr2){
Array.prototype.contains = function(v) {
for (var i = this.length - 1; i >= 0; i--) {
if (this[i] == v) {
return 1;
}
}
return 0;
} arr1 = arr1.sort();
arr2 = arr2.sort();
var ein12 = [], ein1 = [], ein2 = []; for (var i = arr1.length - 1; i >= 0; i--) {
if(arr2.contains(arr1[i])){
ein12.push(arr1[i]);
}else{
ein1.push(arr1[i]);
}
} for (var i = arr2.length - 1; i >= 0; i--) {
if(!arr1.contains(arr2[i])){
ein2.push(arr2[i]);
}
} return { 'ein12': ein12, 'ein1': ein1, 'ein2': ein2 }
}
// a=[1,2,3,2,3];
// b=[2,3,4,3,4];
// compareArr1(a,b);
        // O(m*n + m + n) -> O(n^2)
function compareArr2(arr1, arr2) { function delDup(arr) {
for (var i = arr.length - 1; i >= 1; i--) {
if(arr[i]==arr[i-1]){
arr.splice(i,1);
}
}
} arr1 = arr1.sort();
arr2 = arr2.sort(); delDup(arr1);
delDup(arr2); var ein12 = [], ein1 = arr1.slice(0, arr1.length), ein2 = arr2.slice(0, arr2.length); for (var i = arr1.length - 1; i >= 0; i--) {
for (var j = arr2.length - 1; j >= 0; j--) {
if (arr1[i] == arr2[j]) {
ein12.push(arr1[i]);
ein1.splice(i, 1);
ein2.splice(j, 1);
break;
}
}
}
return { 'ein12': ein12, 'ein1': ein1, 'ein2': ein2 }
}
// a=[1,2,3,2,3];
// b=[2,3,4,3,4];
// compareArr2(a,b);
        // O(2m+2n+m+n) -> O(3(m+n)) -> O(n)
function compareArr3(arr1, arr2){
function arr2obj(obj,arr) {
for (var i = arr.length - 1; i >= 0; i--) {
obj['_' + arr[i]]=arr[i];
}
return obj;
}
var obj12 = {}, obj1 = {}, obj2 = {};
arr2obj(obj1,arr1);
arr2obj(obj2,arr2);
arr2obj(obj12,arr1);
arr2obj(obj12,arr2); var ein12 = [], ein1 = [], ein2 = []; for(var k in obj12){
if(obj1[k] && obj2[k])
{
ein12.push(obj12[k]);
}else if(obj1[k]){
ein1.push(obj12[k]);
}else{
ein2.push(obj12[k]);
}
} return { 'ein12': ein12, 'ein1': ein1, 'ein2': ein2 }
}
// a=[1,2,3,2,3];
// b=[2,3,4,3,4];
// compareArr3(a,b);

Think more, and you can do better.