Leetcode 1013. Pairs of Songs With Total Durations Divisible by 60

题目描述(传送门)

In a list of songs, the i-th song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i < j with (time[i] + time[j]) % 60 == 0.

Example :

Input: [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60

Input: [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.

Note :

1 <= time.length <= 60000
1 <= time[i] <= 500

Code

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        if(time == null || time.length <= 1)return 0;
        int result = 0;
        int zeroNum = 0;
        //对60取余
        for(int i = 0; i < time.length;i++){
            time[i] = time[i] % 60;
            if(time[i] == 0)zeroNum++;
        }
        //排序
        Arrays.sort(time);
        int left = 0+zeroNum;
        int right = time.length-1;
        //滑动窗遍历
        while(left < right){
            if(time[left]+time[right] == 60){
                int leftNum = 0;
                int rightNum = 0;
                while(time[left] == time[left+leftNum]){
                    leftNum++;
                }
                while(time[right] == time[right-rightNum]){
                    rightNum++;
                }
                if(time[left] == time[right]){
                    result = result + leftNum*(leftNum-1)/2;
                    break;
                }
                result = result + leftNum*rightNum;
                left += leftNum;
                right -= rightNum;
            }else if(time[left]+time[right]>60){
                right--;
            }else{
                left++;
            }
        }
        //对0特殊处理
        if(zeroNum >= 2){
            return result + zeroNum*(zeroNum-1)/2;
        }
        return result;
    }
}

2.优化了一下

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        if(time == null || time.length <= 1)return 0;
        int result = 0;
        int[] data = new int[61];
        //对60取余
        for(int i = 0; i < time.length;i++){
            data[time[i] % 60] = data[time[i]%60]+1;
        }
        //互补的两个相乘
        for(int i = 1; i < data.length/2;++i){
            result += data[i]*data[60-i];
        }
        //30可以自补
        result += data[30]*(data[30]-1)/2;
        //0也可以自补
        result += data[0]*(data[0]-1)/2;
        return result;
    }
}

你可能感兴趣的:(Leetcode,java)