1679. Max Number of K-Sum Pairs
Question
You are given an integer array
numsand an integerk.In one operation, you can pick two numbers from the array whose sum equals
kand remove them from the array.Return the maximum number of operations you can perform on the array.
Solution
两种思路,第一种,哈希表统计总数,然后逐个排除。
每次从数组中取一个数,先查询寻找的target是否在哈希表内。
如果表内存在target,则将target的计数减一,对数加一。
如果target不在表内,则将当前的数字加入表内。
最后返回结果。时间复杂度为O(n)。
Code
1  | class Solution {  | 
Solution 2
第二种思路,先排序。
然后双指针放在首尾。
当两者的和等于目标值时增加计数器,并移动两个指针。
当两者的和大于目标值时,右侧指针左移。
当两者的和小于目标值时,左侧指针右移。
最后返回结果。由于有排序存在,因此时间复杂度为O(nlogn) + O(n)。
Code
1  | class Solution {  | 
1679. Max Number of K-Sum Pairs
https://xuanhe95.github.io/2022/05/04/1679-Max-Number-of-K-Sum-Pairs/
