1. 程式人生 > >和為S的兩個數字/和為S的連續正數序列

和為S的兩個數字/和為S的連續正數序列

1.和為S的兩個數字,牛客網ac

其實同leetcode第一題兩數之和一樣,

雙指標,從兩邊逼近。

class Solution {
public:
	vector<int> FindNumbersWithSum(vector<int> array, int sum) {
		int left = 0, right = array.size() - 1;
		int flag = 0;//標記存不存在兩數滿足和sum
		int min_left, min_right;
		vector<int>res;
		if (right <
1)return res; int minMulti = array[right] * array[right]; while (left<right) { if (array[left] + array[right] == sum) { flag = 1; if (minMulti>array[left] * array[right]) { min_left = array[left]; min_right = array[right]; minMulti = min_left*min_right; }
left++; right--; } else if (array[left] + array[right] < sum) left++; else right--; } if (!flag)return res; res.push_back(min_left); res.push_back(min_right); return res; } };

2.和為S的連續正數序列. 時間複雜度O(n)

相似的思路,雙指標(滑動視窗方法)
當總和小於sum,大指標繼續+
否則小指標+

class Solution {
public: //滑動視窗,雙指標 vector<vector<int>> FindContinuousSequence(int sum) { vector<vector<int>>res; if (sum <= 1)return res; int begin = 1, end = 2;//和為正數,連續序列(至少兩個數) while (begin < end&& end <= sum / 2 + 1) { int SumCurr = (begin + end)*(end - begin + 1) / 2;//當前視窗和 if (SumCurr < sum) end++; else if (SumCurr>sum) begin++; else { vector<int>tempres; int temp = begin; while (temp != end+1) tempres.push_back(temp++); res.push_back(tempres); begin++; end++; } } return res; } };