题目描述#

给你一个整数数组 nums 和一个整数 k

每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。

返回你可以对数组执行的最大操作数。

思路#

通过一次遍历数组,和两数之和一样,每次先看看哈希表中是否有k−nums[i],有就去掉哈希表中的一个 k−nums[i],同时把答案加一,没有就把nums[i]加入哈希表。

代码#

我的解答

class Solution {
    public int maxOperations(int[] nums, int k) {
        Map<Integer, Integer> cnt = new HashMap<>();
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            int need = k - nums[i];
            Integer value = cnt.get(need);
            if (value != null && value > 0) {
                if (value == 0) {
                    cnt.remove(need);
                } else {
                    cnt.put(need, value - 1);
                }
                ans++;
            } else {
                cnt.merge(nums[i], 1, Integer::sum);
            }
        }
        return ans;
    }
}

0x3f

class Solution {
    public int maxOperations(int[] nums, int k) {
        HashMap<Integer, Integer> cnt = new HashMap<>();
        int ans = 0;
        for (int x : nums) {
            int c = cnt.getOrDefault(k - x, 0);
            if (c > 0) {
                cnt.put(k - x, c - 1);
                ans++;
            } else {
                cnt.merge(x, 1, Integer::sum);
            }
        }
        return ans;
    }
}
本站总访问量  ·  访客数
你的IP 获取中…