力扣面试(五)

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

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

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

输入:nums = [1,2,3,4], k = 5
输出:2
解释:开始时 nums = [1,2,3,4]:
- 移出 1 和 4 ,之后 nums = [2,3]
- 移出 2 和 3 ,之后 nums = []
不再有和为 5 的数对,因此最多执行 2 次操作。

思路:

先将数据进行从小到大排序,然后从队列两侧进行查找,这样性能会更高

int compareInts(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}

int maxOperations(int* nums, int numsSize, int k){
     qsort(nums, numsSize, sizeof(int), compareInts);

    int operations = 0;
    int left = 0; // Start from the beginning of the array
    int right = numsSize - 1; // Start from the end of the array

    while (left < right) {
        int sum = nums[left] + nums[right];

        if (sum == k) {
            // Found a pair that sums up to k
            operations++;
            left++; // Move the left pointer one step to the right
            right--; // Move the right pointer one step to the left
        } else if (sum < k) {
            // Increase the sum by moving the left pointer to the right
            left++;
        } else {
            // Decrease the sum by moving the right pointer to the left
            right--;
        }
    }

    return operations;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值