[Leetcode学习-c++&java]Pairs of Songs With Total Durations Divisible by 60

问题:Jump Game I

难度:medium

说明:

给一个碟片播放时长数组,然后把 两张 碟片播放时长 相加 % 60 == 0 的所有组合数统计出来。

题目连接:https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/

相关算法:https://blog.csdn.net/qq_28033719/article/details/110553039

[洛谷刷题-C++]P3131-Subsequences Summing to Sevens S

输入范围:

  • 1 <= time.length <= 6 * 104
  • 1 <= time[i] <= 500

输入案例:

Example 1:
Input: time = [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

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

我的代码:

我也是佛了,就 leetcode 跑 c ++ 速度比 java 慢 40 多倍,排行榜还能到93%,但是内存优势还是在那里的。

 

这道题跟 连续相加 % 7 == 0的题目一样,把两个余数相同的 数 组合一起 就是能够被 60 整除,不过有点不同是 这道题是 一个数 + 另一个数,和 一个数 - 另一个数区别。

所以也是:

1、求出并统计所有余数(不需要连续)

2、把两余数互补的相乘(余数 0,30是特例)

c++:

class Solution {
public:
	int numPairsDivisibleBy60(vector<int>& time) {
        int count = 0, len = time.size(), hmap[60]{0};
		for (int i = 0; i < len; i++) 
			hmap[time[i] % 60] ++;
		for (int i = 1; i < 30; i++)
			if(hmap[i]) count += hmap[i] * hmap[60 - i];
		return count + (hmap[30] * (hmap[30] - 1) >> 1) + (hmap[0] * (hmap[0] - 1) >> 1);
	}
};

java:

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int count = 0, len = time.length;
        int hmap[] = new int[60];
		for (int i = 0; i < len; i++) 
			hmap[time[i] % 60] ++;
		for (int i = 1; i < 30; i++)
			if(hmap[i] != 0) count += hmap[i] * hmap[60 - i];
		return count + (hmap[30] * (hmap[30] - 1) >> 1) + (hmap[0] * (hmap[0] - 1) >> 1);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/110917497