1. 问题描述: 给定一个有序递增数组nums,找到所有两个和为target的数值对[number1, number2],如果存在则输出所有的数值对,否则返回[-1, -1]。
举例1:
输入:nums=[1,2,3,4,5,6,7], target = 7
输出:[1, 6], [2, 5], [3, 4]
举例2:
输入:nums=[1,2,3,4,5,6,7], target = 15
输出:[-1, -1]
2. 求解分析:借助一趟快速排序查找的思路。
3. C++代码实现
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> selectNumbers(vector<int> nums, int target){
vector<vector<int>> results;
int left = 0, right = nums.size() - 1;
int flag = 0;
while(left < right){
if(2 * nums[right] < target || nums[left] >= target)
break;
if(target - nums[left] > nums[right] && left < right)
++ left;
else if(target - nums[left] < nums[right] && left < right)
--right;
else{
vector<int> temp;
temp.push_back(nums[left]);
temp.push_back(nums[right]);
results.push_back(temp);
++ left;
-- right;
flag = 1;
}
}
if(flag == 0){
vector<int> temp;
temp.push_back(-1);
temp.push_back(-1);
results.push_back(temp);
}
return results;
}
int main(){
vector<int> numbers{1,2,3,4,5,6,7};
int target = 0; // target = 0 or 7 or 14 or 15...
vector<vector<int>> res;
res = selectNumbers(numbers, target);
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res[0].size(); j++){
if(j == 0)
cout << '[';
if(j < res[0].size()-1)
cout << res[i][j] << ',';
if(j == res[0].size()-1 && i != res.size() - 1)
cout << res[i][j] << ']' << ',';
if(j == res[0].size()-1 && i == res.size() - 1)
cout << res[i][j] << ']';
}
}
return 0;
}
4. 性能分析:
时间复杂度:
网友评论