1013. Pairs of Songs With Total Durations Divisible by 60

time >=1 and <= 500, so sum >= 2 and sum <= 1000
there are 16 numbers in this interval divisible by 60

from 60 to 960, so the problem becomes find the number of pairs with
sum of 60...960

    class Solution {
        public int numPairsDivisibleBy60(int[] time) {
            int ret = 0;
            int[] counter = new int[501];
            for (int i = 0; i < time.length; ++i) {
                for (int j = 1; j <= 16; ++j) {
                    int target = j * 60 - time[i];
                    if (target <= 0 || target > 500) continue;
                    if (counter[target] != 0) ret += counter[target];
                }
                counter[time[i]] += 1;
            }
            return ret;
        }
    }

And after ac, I saw a better solution in discussion area.

It's really great.

            public int numPairsDivisibleBy60(int[] time) {
            int c[]  = new int[60], res = 0;
            for (int t : time) {
                res += c[(60 - t % 60) % 60];
                c[t % 60] += 1;
            }
            return res;
        }

猜你喜欢

转载自www.cnblogs.com/exhausttolive/p/10568880.html