Two Sum - Difference equals to target
ID: 610; medium
Solution 1 (Java)
public class Solution {
/**
* @param nums: an array of Integer
* @param target: an integer
* @return: [num1, num2] (num1 < num2)
*/
public int[] twoSum7(int[] nums, int target) {
int[] res = new int[2];
target = Math.abs(target);
for (int i = 0, j = 1; j < nums.length; j++) {
while (i < j && nums[j] - nums[i] > target) {
i++;
}
if (i != j && nums[j] - nums[i] == target) {
res[0] = nums[i];
res[1] = nums[j];
if (res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
return res;
}
}
return res;
}
}Notes
Two pointers
iandjWe move the
ipointer in this solution to narrow down the range of the two numbers.Time complexity:
O(n)Space complexity:
O(1)
Solution 2 (Java)
Notes
This solution is also the two pointers method, but we move the j pointer. We make sure that j is always larger than i, so we do not need to check for the increasing order in the final answer.
Time complexity:
O(n)Space complexity:
O(1)
Last updated
Was this helpful?