leetcode拓展题1
题目:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使他们的和正好为S,如果有多对数字的和为S,则输出两个数的乘积最小的(或最大)
//假设输出乘积最小的一组
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.size() < 2) return vector<int>();
int min_product = INT_MAX;
int resA = 0;
int resB = 0;
bool flag = false;
int left = 0;
int right = nums.size() - 1;
while(left < right)
{
if(nums[left] + nums[right] < target) left++;
else if(nums[left] + nums[right] > target) right--;
else
{
int curSum = nums[left] + nums[right];
if(curSum < min_product)
{
flag = true;
resA = nums[left];
resB = nums[right];
}
left++;
right--;
}
}
if(flag) return vector<int>{resA,resB};
else return vector<int>();
}
};
//假设输出乘积最大的一组
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.size() < 2) return vector<int>();
int max_product = INT_MIN;
int resA = 0;
int resB = 0;
bool flag = false;
int left = 0;
int right = nums.size() - 1;
while(left < right)
{
if(nums[left] + nums[right] < target) left++;
else if(nums[left] + nums[right] > target) right--;
else
{
int curSum = nums[left] + nums[right];
if(curSum > max_product)
{
flag = true;
resA = nums[left];
resB = nums[right];
}
left++;
right--;
}
}
if(flag) return vector<int>{resA,resB};
else return vector<int>();
}
};