zoukankan      html  css  js  c++  java
  • LeetCode 1010. 总持续时间可被 60 整除的歌曲 Java

    最先想到的两重for循环,超时,输入的数组很大,一整个页面的数,人直接傻了

    class Solution {
        public int numPairsDivisibleBy60(int[] time) {
            int count = 0;
            for(int i=0;i<time.length - 1;i++){
                for(int j=i+1;j<time.length;j++){
                    if((time[i] + time[j]) % 60 == 0){
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

    接下来运用余数的思想。一个数除以60的余数为0~59,建立一个数组remainder保存余数出现的次数。
    先不考虑余数为0和30的情况。
    剩下的余数相加为60则说明可以整除。建立头尾两个指针,1与59,2与58...,如果1有m个,2有n个,那么组合起来是m * n,为count的个数。
    如果余数为0或30,假设余数为0的数有k个,那么k*(k-1)/2,为count的个数。
    最后返回count。

    class Solution {
        public int numPairsDivisibleBy60(int[] time) {
            int count = 0;
            int remainder[] = new int[60];
            for(int i=0;i<time.length;i++){
                remainder[time[i] % 60]++;
            }
            count += remainder[0]*(remainder[0]-1)/2;
            count += remainder[30]*(remainder[30]-1)/2;
            int j = 1;
            int k = 59;
            while(j<k){
                count += remainder[j++] * remainder[k--];
            }
            return count;
        }
    }
    
  • 相关阅读:
    前端PHP入门-001-为什么学习PHP?
    PowerDesigner逆向生成
    Tomcat7项目迁移到Tomcat8中文乱码问题
    通过反射获取T.class代码片段
    pdf预览-js版本
    一般处理程序下载
    .net预览功能
    资源整理
    二、编译安装LAMP之httpd-2.4.4
    HTTP之缓存
  • 原文地址:https://www.cnblogs.com/yu-jiawei/p/12955918.html
Copyright © 2011-2022 走看看