[Leetcode学习-c++&java]Max Number of K-Sum Pairs

46 篇文章 0 订阅

问题:

难度:medium

说明:

给出一个数组,还有K,求数组内 有多少个 两两相加 得到 K值 的对数,每找到一对,就移出数组,那么数组内可以弄出多少对这样的元素。

题目连接:https://leetcode.com/problems/max-number-of-k-sum-pairs/

输入范围:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109

输入案例:

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.

我的代码:

水题,一开始我想到了用 cache ,毕竟这道题确实和 tow sum 一样意思,然后我看其他代码居然还可以排序一边,然后再用双指针处理,确实高明。

先用cache:

Java:

class Solution {
    private static Map<Integer, Integer> cache = new HashMap<>();
    public int maxOperations(int[] nums, int k) {
        int count = 0;
        for(int i : nums) {
            int temp = k - i;
            if(temp > 0) {
                if(cache.getOrDefault(temp, 0) > 0){
                    count ++;
                    cache.put(temp, cache.get(temp) - 1);
                } else cache.put(i, cache.getOrDefault(i, 0) + 1);
            }
        }
        for(Integer i : cache.keySet()) cache.put(i, 0); // 不用删除节点,暴力清零快点,java的map红黑树就是创建和删除节点麻烦
        return count;
    }
}

再改为 sort 和双指针:

Java:

class Solution {
    public int maxOperations(int[] nums, int k) {
        Arrays.sort(nums);
        int count = 0, left = 0, right = nums.length - 1;
        while(right > left) {
            if(nums[right] + nums[left] < k) left ++;
            else if(nums[right] + nums[left] > k) right --;
            else {
                count ++; right --; left ++;
            }
        }
        return count;
    }
}

C++:

class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int count = 0, left = 0, right = nums.size() - 1;
        while(right > left) {
            if(nums[right] + nums[left] < k) left ++;
            else if(nums[right] + nums[left] > k) right --;
            else {
                count ++; left ++; right --;
            }
        }
        return count;
    }
};

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值