610 · Two Sum - Difference equals to target
Algorithms
Medium
Description
Given an sorted array of integers, find two numbers that their difference equals to a target value.
Return a list with two number like [num1, num2] that the difference of num1 and num2 equals to target value, and num1 is less than num2.
It’s guaranteed there is only one available solution.
Note: Requires O(1) space complexity to comple
Example
Example 1:
Input: nums = [2, 7, 15, 24], target = 5
Output: [2, 7]
Explanation:
(7 - 2 = 5)
Example 2:
Input: nums = [1, 1], target = 0
Output: [1, 1]
Explanation:
(1 - 1 = 0)
Related Knowledge
学习《算法求职课——百题精讲》课程中的10.5两数和-差等于目标值-视频讲解相关内容 ,了解更多相关知识!
Tags
Related Problems
1879
Two Sum VII
Hard
587
Two Sum - Unique pairs
Medium
608
Two Sum II - Input array is sorted
Medium
56
Two Sum
Easy
1797
optimalUtilization
Easy
607
Two Sum III - Data structure design
Easy
609
Two Sum - Less than or equal to target
Medium
443
Two Sum - Greater than target
Medium
689
Two Sum IV - Input is a BST
Medium
1187
K-diff Pairs in an Array
Easy
解法1:先排序后用双指针。这里用逆向双指针好像不太可行,因为假设target=6, 两个符合条件的数的索引可能是(1,7), (3,9), (7,12),等等。假如我们设p1=0, p2=12,但是nums[p2]-nums[p1]>6,那我们是p1++还是p2–呢? 两个都进行就复杂了。
这里用同向双指针比较好。一开始p1=0, p2=1。当两指针指向的值的difference<target时,p2++,当difference>target时,p1++(但这里要注意p1不能超过p2,若p1==p2,则p2++),若difference=target,则返回p1,p2。
这里要先用一个class把数组的index保存下来,因为sort后顺序会乱。另外一个要注意的地方是如果用stl::sort的话,必须把less_pair()定义成static,因为sort是global function(),似乎只能调用global或static function?
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class PairClass {
public:
PairClass(int i=0, int v=0) : index(i), val(v) {}
int index;
int val;
};
static bool less_pair(const PairClass &first, const PairClass &second) {
return first.val < second.val;
}
vector<int> twoSum7(vector<int> &nums, int target) {
int len=nums.size();
vector<int> result;
if (len<=1) return result;
int p1=0, p2=1;
//initialize pairs
vector<PairClass> pairs(len);
for (int i=0; i<len; ++i)
pairs[i]=PairClass(i, nums[i]);
sort(pairs.begin(), pairs.end(), less_pair);
while(p2<len && p1<p2) {
int diff = pairs[p2].val-pairs[p1].val;
if (diff == abs(target)) {
result.push_back(min(pairs[p1].index, pairs[p2].index)+1); //vector index begins from 1
result.push_back(max(pairs[p1].index, pairs[p2].index)+1); //vector index begins from 1
return result;
} else if (diff < abs(target)) {
p2++;
} else {
p1++;
if (p1==p2) p2++;
}
}
return result;
}
int main()
{
//vector<int> nums={7,2,15,24};
//vector<int> ret=twoSum7(nums, -5);
//for (int i:ret) cout<<i<<" ";
//cout<<endl;
//vector<int> nums={1,0,1};
//vector<int> ret=twoSum7(nums, 0);
//for (int i:ret) cout<<i<<" ";
//cout<<endl;
vector<int> nums={1,2,33,23,2423,33,23,1,7,6,8787,5,33,2,3,-23,-54,-67,100,400};
vector<int> ret=twoSum7(nums, 393);
for (int i:ret) cout<<i<<" ";
cout<<endl;
return 0;
}
为什么同向双指针可以work? 看下面这张图就知道了。P2就相当于Y,P1就相当于X。最开始坐标在(0,1),蓝色图标箭头显示了该算法是如何一步一步走到正确位置的。看懂了就可以明白为什么p2-p1>target时是p1++而不是p2–, p2-p1<target时是p2++而不是p1–,因为不能走回头路。
同向双指针的另外一种写法。
struct ResultType {
int value;
int index;
ResultType(int v = 0, int i = 0) : value(v), index(i) {}
};
struct cmp {
bool operator() (ResultType & a, ResultType & b) {
if (a.value < b.value) return true;
if (a.value == b.value) return a.index < b.index;
return false;
}
} compare;
class Solution {
public:
/**
* @param nums: an array of Integer
* @param target: an integer
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum7(vector<int> &nums, int target) {
int n = nums.size();
if (n == 0) return vector<int>();
vector<ResultType> nums2;
for (int i = 0; i < n; ++i) {
nums2.push_back(ResultType(nums[i], i));
}
sort(nums2.begin(), nums2.end(), compare);
int p1 = 0, p2 = 1;
if (target < 0) target = -target;
while(p2 < n) {
int diff = nums2[p2].value - nums2[p1].value;
if (diff == target) {
return vector<int>{min(nums2[p1].index, nums2[p2].index) + 1, max(nums2[p1].index, nums2[p2].index) + 1};
} else if (diff < target) {
p2++;
} else {
p1++;
if (p1 == p2) p2++;
}
}
return vector<int>();
}
};
同向双指针经典模板的解法:
i 是左指针,j是右指针。注意因为i,j不能相同,j=max(j, i+1)。
class Solution {
public:
/**
* @param nums: an array of Integer
* @param target: an integer
* @return: [num1, num2] (index1 < index2)
*/
vector<int> twoSum7(vector<int> &nums, int target) {
int len = nums.size();
int i = 0, j = 1;
target = abs(target);
for (i = 0; i < len; i++) {
j = max(j, i + 1);
while (j < len && nums[j] - nums[i] < target) {
j++;
}
if (j >= len) break;
if (nums[j] - nums[i] == target) {
return {nums[i], nums[j]};
}
}
return {};
}
};
解法2:Hash Table (unordered_set或unordered_map)
vector<int> twoSum7(vector<int> &nums, int target) {
unordered_map<int, int> hashMap;
vector<int> result;
for (int i=0; i<nums.size(); ++i) {
int temp=nums[i]-target;
if (hashMap.find(temp)!=hashMap.end()) {
result.push_back(hashMap[temp]+1);
result.push_back(i+1);
return result;
}
temp=nums[i]+target;
if (hashMap.find(temp)!=hashMap.end()) {
result.push_back(hashMap[temp]+1);
result.push_back(i+1);
return result;
}
hashMap[nums[i]]=i;
}
}
三刷: 新的模板。
class Solution {
public:
/**
* @param nums: an array of Integer
* @param target: an integer
* @return: [num1, num2] (index1 < index2)
*/
vector<int> twoSum7(vector<int> &nums, int target) {
int n = nums.size();
//sort(nums.begin(), nums.end());
int start = 0, end = 0;
vector<int> res;
bool isNeg = false;
if (target < 0) isNeg = true;
while (end < n) {
if (start < end && nums[end] - nums[start] == abs(target)) {
return {nums[start], nums[end]};
}
end++;
while (nums[end] - nums[start] > abs(target)) {
start++;
}
}
return {};
}
};
下面这个模板更好
class Solution {
public:
/**
* @param nums: an array of Integer
* @param target: an integer
* @return: [num1, num2] (index1 < index2)
*/
vector<int> twoSum7(vector<int> &nums, int target) {
vector<int> res;
sort(nums.begin(), nums.end());
int n = nums.size();
int left = 0, right = 0;
int diff = 0;
while (right < n) {
right++;
while (right < n && nums[right] - nums[left] > abs(target)) {
left++;
}
if (left < right && nums[right] - nums[left] == abs(target)) {
res.push_back(nums[left]);
res.push_back(nums[right]);
return res;
}
}
return res;
}
};