天天看點

2019-12-30-LeetCode【1010. 總持續時間可被 60 整除的歌曲】

1010. 總持續時間可被 60 整除的歌曲

在歌曲清單中,第 i 首歌曲的持續時間為 time[i] 秒。

傳回其總持續時間(以秒為機關)可被 60 整除的歌曲對的數量。形式上,我們希望索引的數字  i < j 且有 (time[i] + time[j]) % 60 == 0。

           
示例 1:

輸入:[30,20,150,100,40]
輸出:3
解釋:這三對的總持續時間可被 60 整數:
(time[0] = 30, time[2] = 150): 總持續時間 180
(time[1] = 20, time[3] = 100): 總持續時間 120
(time[1] = 20, time[4] = 40): 總持續時間 60
示例 2:

輸入:[60,60,60]
輸出:3
解釋:所有三對的總持續時間都是 120,可以被 60 整數。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
           

提示:

  1. 1 <= time.length <= 60000

  2. 1 <= time[i] <= 500

思路

原數組的每一個元素對60取餘,将出現的次數儲存在一個60個元素的數組中。對于0和30特殊處理配對的數目為count[0]*(count[0]-1)/2、count[30]*(count[30]-1)/2;對于其他的數1~29,31~59,對數為count[i]*count[60-i];

代碼

class Solution {
public:
    // int numPairsDivisibleBy60(vector<int>& time) {
    //     int len=time.size();
    //     int res=0;
    //     for(int i=0;i<len;i++)
    //     {
    //         for(int j=i+1;j<len;j++)
    //         {
    //             if((time[i]+time[j])%60==0)
    //             res++;
    //         }
    //     }
    //     return res;
        
    // }

    int numPairsDivisibleBy60(vector<int>& time) {
        int res=0;
        int count[60]={0}; //下表代表餘數 元素代表出現的次數
        int len=time.size();
        for(auto i:time)
            count[i%60]++;
        for(int i=1;i<30;i++)
        {
            res+=count[i]*count[60-i];
        }
        res+=count[0]*(count[0]-1)/2;
        res+=count[30]*(count[30]-1)/2;
        return res;
    }
};