iT邦幫忙

0

InterSection

InterSection(集合)

以下會來實作怎麼找尋兩個array的集合


先使用兩個迴圈來實作BigO(n^2)

let array1 = [1,2,3,4,5]
let array2 = [1,3,5,7,9]

function interSection(arrayA, arrayB){
    let result = [] //建立空陣列

    for(let i = 0; i < arrayA.length; i++){
        for(let j = 0; j<arrayB.length; j++){
            if(arrayA[i] === arrayB[j]){
                result.push(arrayA[i]) //塞入該數值
            }
        }
    } return result //回傳結果
}
console.log(interSection(array1,array2)) //[1, 3, 5]

小試身手複習一下Object使用

let c = "Hello"

function count(inputStr){
    let inputArr = inputStr.split('')
    let inputOBJ = {}
    
    for(let i = 0; i<inputArr.length; i++){
        if(!inputOBJ[inputArr[i]]){
            inputOBJ[inputArr[i]] = 1
        }else{
            inputOBJ[inputArr[i]] +=1
        }
    }

    for(let t in inputOBJ){
        if(inputOBJ[t] >= 2){
            console.log(t)
        }
    }
}
count(c) //l

使用Object計算 BigO(n)

let array1 = [1,2,3]
let array2 = [1,3,5]

function Counter(arrayA, arrayB){
    let result = []
    let array3 = arrayA.concat(arrayB)
    let arrayOBJ = {}

    for(let i = 0; i < array3.length; i++){
        if(!arrayOBJ[array3[i]]){ //若false則arrayOBJ{key:1:value:1}
            arrayOBJ[array3[i]] = Number.parseInt(1)
        }else{
            arrayOBJ[array3[i]] += 1 //重複之後key+1
        }
        console.log(arrayOBJ)
       
    } 
    for(let property in arrayOBJ){ //
        console.log(result)
        if(arrayOBJ[property] >= 2){ //找尋arrayOBJ的key有沒有value >=2
            result.push(property) //並且塞入result
        }
    }return result
}
console.log(Counter(array1, array2)) //[ '1', '3' ]

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言