【Lintcode】572. Music Pairs
題目地址:
https://www.lintcode.com/problem/music-pairs/description
給定一個陣列 A A A,問能找到多少組二元組使得兩數之和是 60 60 60的倍數。順序不同算同一個組。題目保證 A A A只含 1 ∼ 60 1\sim 60 1∼60的數。
先求一下每個數出現的次數,設 c [ i ] c[i] c[i]是 i i i出現次數,那麼對於 k + ( 60 − k ) k+(60-k) k+(60−k)這樣的數對,有 c [ k ] c [ 60 − k ] c[k]c[60-k] c[k]c[60−k]個組合,而對於 30 + 30 30+30 30+30和 60 + 60 60+60 60+60的組合,各有 c [ 30 ] ( c [ 30 ] − 1 ) c[30](c[30]-1) c[30](c[30]−1)和 c [ 60 ] ( c [ 60 ] − 1 ) c[60](c[60]-1) c[60](c[60]−1)個。求個總和即可。程式碼如下:
public class Solution {
/**
* @param musics: the musics
* @return: calc the number of pair of music
*/
public long musicPairs(int[] musics) {
// write your code here
long[] count = new long[61];
for (int music : musics) {
count[music]++;
}
long res = 0;
for (int i = 1; i < 30; i++) {
res += count[i] * count[60 - i];
}
for (int i = 30; i <= 60; i += 30) {
if (count[i] >= 2) {
res += count[i] * (count[i] - 1) / 2;
}
}
return res;
}
}
時間複雜度 O ( l A ) O(l_A) O(lA),空間 O ( 1 ) O(1) O(1)。
相關文章
- Palindrome PairsAI
- Swap Nodes in PairsAI
- Music Poster
- 024,Swap Nodes in PairsAI
- 24. Swap Nodes in PairsAI
- Leetcode Swap Nodes in PairsLeetCodeAI
- CF1762F Good PairsGoAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- 1512. Number of Good PairsGoAI
- LeetCode-Palindrome PairsLeetCodeAI
- 532. K-diff Pairs in an ArrayAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- [ubuntu] 使用 apple musicUbuntuAPP
- Vim auto-pairs設定選項AI
- 【LeetCode】Palindrome Pairs(336)LeetCodeAI
- CF Div. 3 C Beautiful Triple PairsAI
- music-lake專案梳理
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- Diff-prime Pairs(思維+素數篩)AI
- LeetCode677. Map Sum PairsLeetCodeAI
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- Leetcode 線性表 Swap Nodes in PairsLeetCodeAI
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- vue-music 音樂網站Vue網站
- web podcast player & music player All In OneWebAST
- Lua中ipairs()和pairs()的區別與使用AI
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation