1010. Pairs of Songs With Total Durations Divisible by 60

53 阅读1分钟

image.png

方法

hashmap

  • key 某数%60的余数
  • value 这个余数出现的次数
  • 类似两数之和
class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int t : time) {
            if (t % 60 == 0) { // 考虑 60,60  60,120配对的情况
                if (map.containsKey(0)) {
                    res += map.get(0);
                }
                map.put(0, map.getOrDefault(0, 0) + 1);
            } else {
                if (map.containsKey(60 - t % 60)) {
                    res += map.get(60 - t % 60);
                }
                map.put(t % 60, map.getOrDefault(t % 60, 0) + 1);
            }
        }
        return res;
    }
}

合并

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int t : time) {
            // combine t % 60 = 0 case, use double %
            if (map.containsKey((60 - t % 60) % 60)) {
                res += map.get((60 - t % 60) % 60);
            }
            map.put(t % 60, map.getOrDefault(t % 60, 0) + 1);
            
        }
        return res;
    }
}

优化

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int res = 0;
        int[] map = new int[60];
        for (int t : time) {
            // combine t % 60 = 0 case, use double %
            res += map[(60 - t % 60) % 60];
            map[t % 60]++;            
        }
        return res;
    }
}