《剑指offer》57--和为 S 的数字[C++]

1. 和为S的两个数字

和为S的两个数字_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力icon-default.png?t=LA92https://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;
    }
};

也可以返回下标:

LeetCode-1. Two Sum [C++]_贫道绝缘子的博客-CSDN博客Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.https://blog.csdn.net/qq_15711195/article/details/122143418

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的连续正数序列

《剑指offer》74--和为S的连续正数序列[C++]_贫道绝缘子的博客-CSDN博客输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序.https://blog.csdn.net/qq_15711195/article/details/121887708

参考文献:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值