|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 这是她 于 2020-5-25 21:21 编辑
总持续时间可被60整除的歌曲
题目:
在歌曲列表中,第 i 首歌曲的持续时间为 time 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 i 和 j 满足 i < j 且有 (time + time[j]) % 60 == 0。
示例1:
- <i>输入:[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</i>
复制代码 示例2:
- <i>输入:[60,60,60]
- 输出:3
- <div>解释:所有三对的总持续时间都是 120,可以被 60 整数。
- </div></i>
复制代码
提示:
- 1 <= time.length <= 60000
- 1 <= time <= 500
代码:
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <string.h>
- using namespace std;
- class Solution
- {
- public:
- int num[61];
- int res;
- int numPairsDivisibleBy60(vector<int>& time) {
- //使用empty判断数组是否为空
- if(time.empty())
- return 0;
-
- //memset()函数原型是extern void *memset(void *buffer, int c, int count)
- //buffer:为指针或是数组, c:是赋给buffer的值,count:是buffer的长度.
- //Memset 用来对一段内存空间全部设置为某个字符,一般用在对定义的字符串进行初始化为‘ ’或‘/0’;
- memset(num,0,sizeof num );
-
- //这是一个循环--对60求模
- for(int i = 0; i < time.size(); i++)
- {
- time[i] %= 60;
- num[time[i]]++;
- }
-
- //对数组元素进行排序
- //sort(begin,end),表示一个范围
- //需要加上头文件#include <algorithm>
- sort(time.begin(),time.end());
-
- for(int i = 0; i < time.size(); i++)
- {
- //break->结束当前循环
- //continue-> 跳出当前循环,实行下一循环
- if(time[i] >= 30) break;
- if(time[i] == 0) continue;
- res += num[60 - time[i]];//寻找time[i]所对应的那个相加为60的数,返回那个数的个数
- }
-
- //计算30,0相应的个数
- res += (num[30]*(num[30]-1))/2;
- res += (num[0]*(num[0]-1))/2;
- return res;
- }
- };
- int main()
- {
- vector<int> num1 = {30,40,60,80};
- Solution s1;
- int a = s1.numPairsDivisibleBy60(num1);
-
- cout << a << endl;
-
- return 0;
- }
复制代码
https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/solution/jian-dan-de-ji-shu-wen-ti-by-0x404/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems ... ons-divisible-by-60
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
|