iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
0
Software Development

用JS來刷刷HackerRank系列 第 25

(28)HackerRank-Interview-Dictionaries and Hashmaps-Count Triplets(javaScript ans)

題目
Count Triplets
舉例輸入

4 2
1 2 2 4

舉例輸出

2


舉例輸入

6 3
1 3 9 9 27 81

舉例輸出

6



舉例輸入

5 5
1 5 5 25 125

舉例輸出

4

解析
這題給定一陣列[1,2,2,4]
其中 (0,1,3) (0,2,3)的元素互為指數關係
我們要做的是一個陣列以三個為一組,可以拼出幾組指數

function countTriplets(arr, r) {
    let triplets = 0;
    const count = [];
    const pairs = [];
    for (let n = 0; n < arr.length; n++) {
        const i = arr[n]
        const ir = i/r
        if (count[i] === undefined) {
            count[i] = 0; 
            pairs[i] = 0;
        }
        if (pairs[ir]) {
            triplets += pairs[ir]
        }
        if (count[ir]) {
            pairs[i] += count[ir]
        }
        count[i]++
    }
    return triplets;
}

 

上一篇
(27)HackerRank-Interview-Dictionaries and Hashmaps-Sherlock and Anagrams(javaScript ans)
下一篇
(29)HackerRank-Interview-Dictionaries and Hashmaps-Frequency Queries(javaScript ans)
系列文
用JS來刷刷HackerRank29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言