购物车内的商品价格按照升序记录于数组 price
。请在购物车中找到两个商品的价格总和刚好是 target
。若存在多种情况,返回任一结果即可。
示例 1:
输入:price = [3, 9, 12, 15], target = 18
输出:[3,15] 或者 [15,3]
示例 2:
输入:price = [8, 21, 27, 34, 52, 66], target = 61
输出:[27,34] 或者 [34,27]
提示:
1 <= price.length <= 10^5
1 <= price[i] <= 10^6
1 <= target <= 2*10^6
思路:
1、二分查找用来缩小空间,将数组空间缩小至0到第一个大于target的空间。
2、利用对调双指针来判断,具体来说双指针和大于target,high--,小于target则low++,等于则返回两个指针对应的值。
3、没有符合要求的返回空。
代码实现:
class Solution {
public:
vector<int> twoSum(vector<int>& price, int target) {
int low = 0, high = price.size() - 1;
while(low < high)
{
int mid = low + (high - low) / 2;
if(price[mid] > target)
high = mid - 1;
else
low = mid + 1;
}
high = low;
low = 0;
while(low < high)
{
int num = price[low] + price[high];
if(num > target)
--high;
else if(num < target)
++low;
else
return {price[low], price[high]};
}
return {};
}
};