Max Number of K-Sum Pairs
给一个数组, 里面的数字可能会重复, 问里面有多少组不同的数字对, 可以想加成k.
这个题主要是有重复, 所以用counting来做, 然后要判断2个数字是否重复来更新counting的数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public int maxOperations(int[] nums, int k) { int res = 0; Map<Integer, Integer> count = new HashMap<>(); for(int i = 0; i < nums.length; i++) { count.put(nums[i], count.getOrDefault(nums[i], 0) + 1); } for(int i = 0; i < nums.length; i++) { int n = count.getOrDefault(nums[i], 0); int m = count.getOrDefault(k - nums[i], 0); if((nums[i] == k - nums[i] && m > 1)) { // if two numbers are same count.put(nums[i], n - 2); res++; } else if(nums[i] != k - nums[i] && n > 0 && m > 0) { // or two number are diff count.put(nums[i], n - 1); count.put(k - nums[i], m - 1); res++; } } return res; } } |