Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

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));

@kangkang123269
Copy link

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
   }
}

@gswysy
Copy link

gswysy commented Mar 3, 2024

function judge(arrA, arrB) {
    let key = true
    for (const item of arrA) {
        if (!arrB.includes(item)) {
            key = false
            break;
        }
    }
    if (key) {
        if (arrA.length === arrB.length) return 0
        else return 1
    } else {
        key = true
        for (const item of arrB) {
            if (!arrA.includes(item)) {
                key = false
                break;
            }
        }
        if (key) return 2
    }
    return -1
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants