【剑指offer】57、和为s的数字

题目一

输入一个递增排序数组和一个数字s,在数组中查找两个数,使得和为s。如果有多对数字和为s,则输出任意一对。

思路

num1和num2分别代表数组的第一个和最后一个

若 num1 + num2 > s,则将num2向前

若num1 + num2 < s, 则将num1后移

直到找到

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        int length = array.size();
        vector<int> res;
        int start = 0, end = length - 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;
    }
};

题目二

输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。例如输入15,由于1+2+...+6=4+5+6=7+8=15,输出1~5,4~6,7~8

思路

也是和上题思路差不多,首先设置small = 1, big = 2

small~big < s ,那么就增加big

small~big >= s,那么就增加small (相等也要后移small,找出其他解)

直到small到(s+1)/2为止,此时small~big已经已经大于s了

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int>> allRes;
        int slow = 1, fast = 2;
        while (slow < fast)
        {
            int cur = (slow + fast) * (fast - slow + 1) / 2;
            if (cur == sum)
            {
                vector<int> res;
                for (int i = slow; i <= fast; i++)
                    res.push_back(i);
                
                allRes.push_back(res);
                slow++;
            }
            if (cur > sum)
                slow++;
            else
                fast++;
        }
        return allRes;
    }
};

猜你喜欢

转载自www.cnblogs.com/shiganquan/p/9350736.html