1. 程式人生 > 其它 >[Leetcode學習-c++&java]Pairs of Songs With Total Durations Divisible by 60

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

技術標籤:JavaC++

問題: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);
    }
}