1099 Two Sum Less Than K

本文探讨了在给定整数数组中寻找不超过特定阈值K的最大两数之和的有效算法。通过双指针法和排序,实现了高效查找,同时分析了另一种基于哈希表的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 题目

Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1.

Example 1:

Input: A = [34,23,1,24,75,33,54,8], K = 60
Output: 58
Explanation: 
We can use 34 and 24 to sum 58 which is less than 60.

Example 2:

Input: A = [10,20,30], K = 15
Output: -1
Explanation: 
In this case it's not possible to get a pair sum less that 15.

Note:

  1. 1 <= A.length <= 100
  2. 1 <= A[i] <= 1000
  3. 1 <= K <= 2000

2 尝试解

2.1 分析

给定一组整数,要求找出不超过K的最大的两数之和。

因为不是等式,无法用hashmap,可以用双指针法。先将数组排序,然后用左右指针前后移动。如果num[left]+num[right] >= K,则将right向左移动,否则将left向右移动。

该方法的思想是,对于右端的每一个数num[right],找到左端最大的num[left],满足num[right]+num[left] < K。

2.2 代码

class Solution {
public:
    int twoSumLessThanK(vector<int>& A, int K) {
        sort(A.begin(),A.end());
        int result = -1;
        int left = 0, right = A.size()-1;
        while(left < right){
            if(A[left]+A[right] < K){
                result = max(result,A[left]+A[right]);    
                left++;
            }
            else{
                right--;
            }
        }
        return result;
    }
};

3 标准解

3.1 分析

给定所有数都不小于0,不大于1000,还是可以用unordered_set存储所有的数,对于每一个数i,从K-i-1到0查找这些数是否存在。复杂度为O(K*n)。

3.2 代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值