There are two approaches to this problem, first let's look at the brute force approach.
解决此问题的方法有两种,首先让我们看一下蛮力方法。
In the brute force approach, we'll take one array as constant and traverse through the second array. We'll check for every element if it occurs in the first array. If it does, we'll go on to the next element and if it doesn't we'll return false from there.
在蛮力方法中 ,我们将一个数组作为常量并遍历第二个数组。 我们将检查每个元素是否出现在第一个数组中。 如果是这样,我们将继续下一个元素,如果没有,我们将从那里返回false。
First, let's create three arrays,
首先,让我们创建三个数组,
let arr1 = [1, 2, 3];
let arr2 = [1, 5, 4];
let arr3 = [2, 1, 3];
console.log(arr1);
console.log(arr2);
console.log(arr3);
Output
输出量
(3) [1, 2, 3]
(3) [1, 5, 4]
(3) [2, 1, 3]
Let's create a function that takes two arrays and checks if they're equal. We can use the includes method to check if an element occurs in an array.
让我们创建一个接受两个数组并检查它们是否相等的函数。 我们可以使用include方法来检查元素是否出现在数组中。
function compare(arr1, arr2) {
for (let i = 0; i < arr1.length; i++) {
if (!arr2.includes(arr1[i]))
return false;
}
return true;
}
compare(arr1, arr2);
compare(arr1, arr3);
Output
输出量
False
True
Our function works just fine! But let's understand what we're doing here, we're comparing every element of one array for its existence in the second array. If the length of the first array is n and that of the other is m, our code takes a time of O(n*m). Can we do a bit better?
我们的功能正常工作! 但是让我们了解一下我们在做什么,我们正在比较一个数组的每个元素在第二个数组中的存在。 如果第一个数组的长度为n ,另一个数组的长度为m ,则我们的代码将花费O(n * m)的时间 。 我们可以做得更好吗?
When two arrays are the same, they have the same elements. Here the problem is that the elements are not following a particular order. What if we sort the two arrays?
当两个数组相同时,它们具有相同的元素。 这里的问题是元素没有遵循特定的顺序。 如果我们对两个数组排序怎么办?
function compare(arr1, arr2) {
arr1.sort();
arr2.sort();
if (arr1.length != arr2.length)
return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i])
return false;
}
return true;
}
compare(arr1, arr2);
compare(arr1, arr3);
Output
输出量
false
true
When we sort the two arrays if they contain the same elements their order becomes the same. We can then simply check if both the arrays have the same element present at the same index and return true and false otherwise.When we sort the two arrays if they contain the same elements their order becomes the same. We can then simply check if both the arrays have the same element present at the same index and return true and false otherwise.
当我们对两个数组进行排序(如果它们包含相同的元素)时,它们的顺序将相同。 然后我们可以简单地检查两个数组是否在相同的索引处存在相同的元素,否则返回true和false。当对两个数组进行排序时,如果它们包含相同的元素,则它们的顺序将相同。 然后,我们可以简单地检查两个数组是否在相同的索引处存在相同的元素,否则返回true和false。
Let's look at how much optimization we have achieved. Sorting takes O(n*logn) time if the array contains n elements and finally, our comparing function's loop takes O(n) time. Effectively, our code now runs in O(nlogn) time which is a good upgrade from the previous code that took O(n^2) time!
让我们看看我们已经实现了多少优化。 如果数组包含n个元素, 排序将花费O(n * logn)时间 ,最后,我们的比较函数的循环将花费O(n)时间。 实际上,我们的代码现在以O(nlogn)时间运行,这是对以前花费O(n ^ 2)时间的代码的很好升级!