Two Sum - Difference

Given an array of integers, find two numbers that theirdifferenceequals 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.

It's guaranteed there is only one available solution

Example

Given nums =[2, 7, 15, 24], target =5 return[1, 2](7 - 2 = 5)

Note

有点区别。返回的第几个位置,双指针有点烦的。

HashMap就是看一看加/减target在不在Map里面

双指针的话这里同向双指针了,差是递增的!

Code

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 new int[]{map.get(nums[i] + target) + 1, i + 1};
            } else if (map.containsKey(nums[i] - target)) {
                return new int[]{map.get(nums[i] - target) + 1, i + 1};
            } else {
                map.put(nums[i], i);
            }
        }
        return new int[]{};
    }
}

Last updated