iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 23
0
Software Development

用JS來刷刷HackerRank系列 第 27

(29)HackerRank-Interview-Dictionaries and Hashmaps-Frequency Queries(javaScript ans)

題目
Frequency Queries
舉例輸入

8
1 5
1 6
3 2
1 10
1 10
1 6
2 5
3 2

舉例輸出

0
1


舉例輸入

10
1 3
2 3
3 2
1 4
1 5
1 5
1 4
3 2
2 4
3 2

舉例輸出

0
1
1

解析
這題輸入看起來很恐怖,但只是(action, number)
的概念
1:新增一數到陣列中
2:從陣列中刪除該數的出現次數一次。
3:判斷該數是否有在陣列之中有輸出1沒有則輸出0
所以我們只要針對每個動作制定他該做的事
然後慢慢來就可以了

function freqQuery(queries) {
    const frequencies = [];
    const frequencyTracker = [];
    const result = [];

    for (const query of queries) {
        const action = query[0];
        const value = query[1];
        let index;

        if (action === 1 || action === 2) {
            index = frequencies[value];
            frequencyTracker[index] ? --frequencyTracker[index] : null;
        }

        if (action === 1) {
            typeof frequencies[value] === 'undefined' ? frequencies[value] = 1 : ++frequencies[value];
        }

        if (action === 2 && frequencies[value]) {
            --frequencies[value];
        }

        if (action === 1 || action === 2) {
            index = frequencies[value];
            frequencyTracker[index] ? ++frequencyTracker[index] : frequencyTracker[index] = 1;
        }

        if (action === 3) {
            result.push(frequencyTracker[value] > 0 ? 1 : 0);
        }
    }

    return result;
}
 

上一篇
(28)HackerRank-Interview-Dictionaries and Hashmaps-Count Triplets(javaScript ans)
下一篇
(24)HackerRank-Interview-Arrays-Minimum Swaps 2(javaScript ans)
系列文
用JS來刷刷HackerRank30

尚未有邦友留言

立即登入留言