#90 判断两个 Set 是否相同


  • 0

    const isSameSet = (s1, s2) => {
    let diff1 = new Set([...s1].filter(x => !s2.has(x)))
    let diff2 = new Set([...s2].filter(x => !s1.has(x)))
    if(diff1.size || diff2.size) {
    return false
    }
    return true
    }


  • 0

    写的不好,但我能想到的就是这样了

    const isSameSet = (s1, s2) => {
    
       function fn(...rest) {
           let arr = [];
           for (let i = 0; i < rest.length; i++) {
               for (let k of rest[i]) {
                   arr.push(k);
               }
           }
           return new Set(arr);
       }
    
       if (s1.size === s2.size) {
           if (fn(s1, s2).size === s1.size) {
               return true;
           }
           return false;
       }
       return false;
    };

  • 0

    @Reson_a 这个方法使用了set的不重复属性,如果两个set相等,合并后和合并前的size一定相等


  • 0

    		const isSameSet = (s1, s2) => {/* TODO */
    
    			let arr1 = [...s1] , arr2 = [...s2];
    
    			let a = arr1.every(item => arr2.includes(item))
    			let b = arr2.every(item => arr1.includes(item))
    
    			return a && b && arr1.length == arr1.length
    	}
    

  • 0

    const isSameSet = (s1, s2) => /* TODO */{
    var resArr = new Set([]);
    for(let item of s1){
    resArr.add(s2.has(item))
    }
    return !resArr.has(false)
    }
    为什么这样不可以过?


  • 0

    const isSameSet = (s1, s2) => {
    if(s1.size !== s2.size){return false}
    let arr1 = [...s1];
    let arr2 = [...s2];
    let set = new Set([...arr1, ...arr2]);
    let arr3 = Array.from(set);
    return arr3.length === arr2.length
    }


  • 0

    0_1548845360811_#90 判断两个 Set 是否相同.png


  • 0

    const isSameSet = (s1, s2) => {
      return (s1.size==s2.size && new Set([...s1,...s2]).size == s1.size)?true:false
    }
    

  • 0

    @Reson_a 简洁,实用,好办法


  • 0

    @Reson_a 这个是有问题的吧,里面有复杂类型,比如都有{},这个虽然两个的内容一样,但是对象不等也会加进去,长度就不等了


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待