Given an array of integers, find two numbers that their difference
equals to a target value.
where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.\
java
public class Solution {
/*
* @param nums: an array of Integer
* @param target: an integer
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum7(int[] nums, int target) {
// write your code here
if (nums == null || nums.length < 2) {
return new int[]{};
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i] - target)) {
return util(i + 1, map.get(nums[i] - target) + 1);
}
else if (map.containsKey(nums[i] + target)) {
return util(i + 1, map.get(nums[i] + target) + 1);
} else {
map.put(nums[i], i);
}
}
return new int[] {};
}
private int[] util(int p1, int p2) {
if (p1 > p2) {
return new int[] {p2, p1};
} else {
return new int[] {p1, p2};
}
}
}
python
class Solution:
"""
@param: nums: an array of Integer
@param: target: an integer
@return: [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum7(self, nums, target):
# write your code here
if nums is None or len(nums) < 2:
return []
mapping = {}
for i in range(len(nums)):
if nums[i] - target in mapping:
return sorted([i + 1, mapping[nums[i] - target] + 1])
elif nums[i] + target in mapping:
return sorted([i + 1, mapping[nums[i] + target] + 1])
else:
mapping[nums[i]] = i
return []