1. 和为S的两个数字
和为S的两个数字_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
双指针,时间复杂度O(n)。
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
int len = array.size(), start = 0, end = len-1;
while(start < end) {
if(array[start]+array[end] == sum) {
res.push_back(array[start]);
res.push_back(array[end]);
break;
} else if(array[start]+array[end] < sum) start++;
else end--;
}
return res;
}
};
也可以返回下标:
2. 和为S的三个数字
LeetCode-15. 3Sum [C++]_贫道绝缘子的博客-CSDN博客Given an arraynumsofnintegers, are there elementsa,b,cinnumssuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.https://blog.csdn.net/qq_15711195/article/details/122143546
3. 和为S的四个数字
LeetCode-18. 4Sum [C++]_贫道绝缘子的博客-CSDN博客Given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddinnumssuch thata+b+c+d=target? Find all unique quadruplets in the array which gives the sum oftarget.https://blog.csdn.net/qq_15711195/article/details/122143625
4. 和为S的连续正数序列
参考文献: