【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)。
相關文章
- 024,Swap Nodes in PairsAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- 1512. Number of Good PairsGoAI
- CF1762F Good PairsGoAI
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- Baby's Sleep Music
- [ubuntu] 使用 apple musicUbuntuAPP
- Vim auto-pairs設定選項AI
- CF Div. 3 C Beautiful Triple PairsAI
- [LeetCode] 1497. Check If Array Pairs Are Divisible by kLeetCodeAI
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- Diff-prime Pairs(思維+素數篩)AI
- Solution - Atcoder ABC263G Erasing Prime PairsAI
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP