1099. 小于 K 的两数之和
LeetCode第 16 题:最接近的三数之和(C++)_zj-CSDN博客的简单版本
class Solution {
public:int twoSumLessThanK(vector<int>& A, int K) {sort(A.begin(), A.end());int res = -1;for(int i = 0; i < A.size()-1; ++i){int j = i+1;while(j < A.size()){if(A[i]+ A[j] < K){if(A[i]+ A[j] ==K -1) return K-1;//已经最接近了res = max(res, A[i]+ A[j]);++j;}else break;}}return res;}
};
换种写法:
class Solution {
public:int twoSumLessThanK(vector<int>& A, int K) {sort(A.begin(), A.end());int res = -1;for(int i = 0; i < A.size()-1; ++i){int j = i+1;while(j < A.size() && A[i]+ A[j] < K){++j;}if(i != j-1 && A[i]+ A[j-1] < K) res = max(res, A[i]+ A[j-1]);if(res == K-1) return res;}return res;}
};