You are given an integer array nums
and an integer k
.
In one operation, you can pick two numbers from the array whose sum equals k
and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with nums = [1,2,3,4]: - Remove numbers 1 and 4, then nums = [2,3] - Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations.
Example 2:
Input: nums = [3,1,3,4,3], k = 6 Output: 1 Explanation: Starting with nums = [3,1,3,4,3]: - Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
K 和数对的最大数目。
给你一个整数数组 nums 和一个整数 k 。
每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。
返回你可以对数组执行的最大操作数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-number-of-k-sum-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的思路类似two sum,我们需要创建一个hashmap来记录input中的数字,以便找到k - nums[i]。这里我提供两种实现方式,一种只需要扫描数组一次,一种需要扫描数组两次。时间空间复杂度均为O(n)。
扫描一次
扫描一次的做法巧妙的地方在于他对当 nums[i] 正好是K的一半的case的处理。当 nums[i] 正好是K的一半的时候,此时res只 + 1,这样就能跟其他情况merge在一起而无需扫描两遍了。
Java实现
1 class Solution { 2 public int maxOperations(int[] nums, int k) { 3 int res = 0; 4 HashMap<Integer, Integer> map = new HashMap<>(); 5 for (int num : nums) { 6 if (map.getOrDefault(k - num, 0) > 0) { 7 map.put(k - num, map.get(k - num) - 1); 8 res++; 9 } else { 10 map.put(num, map.getOrDefault(num, 0) + 1); 11 } 12 } 13 return res; 14 } 15 }
扫描两次
注意第十行的写法,不能写成 if (k / 2 == key)。这种写法是不能通过所有的case的。
Java实现
1 class Solution { 2 public int maxOperations(int[] nums, int k) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 for (int num : nums) { 5 map.put(num, map.getOrDefault(num, 0) + 1); 6 } 7 8 int res = 0; 9 for (int key : map.keySet()) { 10 if (k == 2 * key) { 11 res += map.get(key) / 2; 12 } else if (map.containsKey(k - key)) { 13 int min = Math.min(map.get(key), map.get(k - key)); 14 res += min; 15 map.put(key, map.get(key) - min); 16 map.put(k - key, map.get(k - key) - min); 17 } 18 } 19 return res; 20 } 21 }