第 29 课

  • [136. 只出现一次的数字](https://leetcode-cn.com/problems/single-number/)
  • [1010. 总持续时间可被 60 整除的歌曲](https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/)


136. 只出现一次的数字

class Solution:
    def singleNumber(self, nums: List[int]) -> int: 
        count = Counter(nums)
        for i in count:
            if count[i] == 1:
                return i
        
        # return reduce(lambda x, y: x ^ y, nums)
        # return sum(set(nums))*2-sum(nums)
class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map= new  HashMap<>();        
        for (int i : nums) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        for (int key : map.keySet()) {            
            if (map.get(key) == 1) return key;
        }
        return -1; // can't find it.
        // 方法二:位运算
        // int ans = 0;
        // for (int i : nums) ans ^= i;        
        // return ans;
    }
}

1010. 总持续时间可被 60 整除的歌曲

class Solution:
    def numPairsDivisibleBy60(self, time: List[int]) -> int:
        ans, d = 0, {}  # 余数
        for t in time:
            x = t % 60
            ans += d.get(60 - x, 0) if x else d.get(0, 0) # 特殊情况 60 的倍数
            d[x] = d.get(x, 0) + 1
        return ans

        # ans, d = 0, [0] * 60
        # for t in time:
        #     t %= 60
        #     ans += d[-t] # -0 = 0, d[t] + d[-t] = 60 or 0
        #     d[t] += 1
        # return ans
class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int[] rem = new int[60];
        int ans = 0;
        for (int t : time){
            int x = t % 60;
            ans += x == 0 ? rem[0] : rem[60 - x];
            // ans += rem[(60 - r) % 60];
            rem[x]++;            
        }
        return ans;
    }
}