这是她 发表于 2020-5-25 21:21:31

C++打开LeetCode的大门---1010(数组)

本帖最后由 这是她 于 2020-5-25 21:21 编辑

                                                                                                                  总持续时间可被60整除的歌曲
题目:
在歌曲列表中,第 i 首歌曲的持续时间为 time 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 i 和 j 满足i < j 且有 (time + time) % 60 == 0。

示例1:
<i>输入:
输出:3
解释:这三对的总持续时间可被 60 整数:
(time = 30, time = 150): 总持续时间 180
(time = 20, time = 100): 总持续时间 120
(time = 20, time = 40): 总持续时间 60</i>示例2:
<i>输入:
输出: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;
      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 %= 60;
                        num]++;
                }
               
                //对数组元素进行排序
                //sort(begin,end),表示一个范围
                //需要加上头文件#include <algorithm>
                sort(time.begin(),time.end());
               
                for(int i = 0; i < time.size(); i++)
                {
                        //break->结束当前循环
                        //continue-> 跳出当前循环,实行下一循环
                        if(time >= 30) break;
                        if(time == 0)continue;
                        res += num];//寻找time所对应的那个相加为60的数,返回那个数的个数
                }
               
                //计算30,0相应的个数
                res += (num*(num-1))/2;
                res += (num*(num-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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

KevinHu 发表于 2020-5-25 21:26:41

领扣?{:10_258:}

小甲鱼的铁粉 发表于 2020-5-25 21:42:05

哇(⊙o⊙)!
页: [1]
查看完整版本: C++打开LeetCode的大门---1010(数组)