LeetCode 1010. 总持续时间可被 60 整除的歌曲 Java

最先想到的两重for循环,超时,输入的数组很大,一整个页面的数,人直接傻了

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int count = 0;
        for(int i=0;i<time.length - 1;i++){
            for(int j=i+1;j<time.length;j++){
                if((time[i] + time[j]) % 60 == 0){
                    count++;
                }
            }
        }
        return count;
    }
}

接下来运用余数的思想。一个数除以60的余数为0~59,建立一个数组remainder保存余数出现的次数。
先不考虑余数为0和30的情况。
剩下的余数相加为60则说明可以整除。建立头尾两个指针,1与59,2与58...,如果1有m个,2有n个,那么组合起来是m * n,为count的个数。
如果余数为0或30,假设余数为0的数有k个,那么k*(k-1)/2,为count的个数。
最后返回count。

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int count = 0;
        int remainder[] = new int[60];
        for(int i=0;i<time.length;i++){
            remainder[time[i] % 60]++;
        }
        count += remainder[0]*(remainder[0]-1)/2;
        count += remainder[30]*(remainder[30]-1)/2;
        int j = 1;
        int k = 59;
        while(j<k){
            count += remainder[j++] * remainder[k--];
        }
        return count;
    }
}
posted @ 2020-05-25 11:32  菜鸡A  阅读(197)  评论(0编辑  收藏  举报