This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
A preface,
I saw an array question when I was reading the questions in May. At that time, I felt quite confused, but now I came back to sort out this topic, and suddenly I understood a lot of things.
Let’s take a look
Two, understand the topic
If A belongs to B, return 1; if B belongs to A, return 2; if both are equal, return 0; otherwise return -1.
3. Solution analysis
For the above topics, the solution idea is as follows:
- Four types of inclusion relation;
- One to one correspondence is required, so sort the two arrays first (general ascending operation);
- To solve the
case4
We’ll deal with it latercase123
In the case.
Four, code implementation
Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:
function arrayInclude (arrA, arrB) {
// Sort arrA and arrB in ascending order
arrA.sort((a, b) = > a - b)
arrB.sort((a, b) = > a - b)
for (let i = 0; i < arrA.length; i++) {
if (arrB.includes(arrA[i])) {
The findIndex method is used to find the index of the current value
let index = arrB.findIndex(value= > arrA[i] === value)
if(index ! == i)return -1 // Resolve case 4
// Delete the index from array A and array B
arrB.splice(index, 1)
arrA.splice(i, 1)
// The index above was deleted, so continue iterating through the current one
i--
}
}
// If B belongs to A, return 2
if (arrA.length > arrB.length) {
return 2;
}
// If A belongs to B, return 1
else if (arrA.length < arrB.length) {
return 1;
}
// Return 0 when the two are equal
else if (arrA.length === arrB.length) {
return 0; }}var a1 = [4.2.3.1.4]
var a2 = [5.2.3.1.4.4]
console.log(arrayInclude(a1, a2)) / / 1
var a3 = [4.2.3.1.4]
var a4 = [2.4.3.1]
console.log(arrayInclude(a3, a4)) / / 2
var a5 = [4.2.3.1.4]
var a6 = [4.2.3.1.4]
console.log(arrayInclude(a5, a6)) / / 0
var a7 = [4.2.3.1.4]
var a8 = [3.2.3.1.4]
console.log(arrayInclude(a7, a8)) // -1
Copy the code
The above is about the inclusion relationship solution, I wonder if it is helpful for friends?
We’ll see you next time at 👋👋👋