-
-
Notifications
You must be signed in to change notification settings - Fork 232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
判断A、B数组的包含关系(值和数量),A属于B返回1,B属于A返回2,两者相等返回0,其他返回-1 #88
Comments
const A = [1, 3, 5, 6, 7];
const B = [1, 3, 5, 6, 8];
function judge(A, B) {
let str1 = A.sort((a, b) => a - b).join("");
let str2 = B.sort((a, b) => a - b).join("");
if(str1 === str2) return 0;
else if (str1.includes(str2)) return 2;
else if (str2.includes(str1)) return 1;
return -1;
}
console.log(judge(A, B)); |
function arrayToFrequencyObject(arr) {
return arr.reduce((obj, item) => {
obj[item] = (obj[item] || 0) + 1;
return obj;
}, {});
}
function compareArrays(A, B) {
const freqA = arrayToFrequencyObject(A);
const freqB = arrayToFrequencyObject(B);
let isASubsetOfB = true;
let isBSubsetOfA = true;
for (let key in freqA) {
if (!(key in freqB && freqA[key] <= freqB[key])) {
isASubsetOfB = false;
break;
}
}
for (let key in freqB) {
if (!(key in freqA && freqB[key] <= freqA[key])) {
isBSubsetOfA = false;
break;
}
}
if(isASubsetOfB && isBSubsetOfA){
return 0; // A and B are equal
} else if(isASubsetOfB){
return 1; // A is a subset of B
} else if(isBSubsetOfA){
return 2; // B is a subset of A
} else{
return -1; // A and B are disjoint
}
} |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: