Lintcode - 610. Two Sum - Difference equals to target

https://www.lintcode.com/problem/610/

two pointers

time: O(n)

space: O(1)

use two pointers, same direction

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) {
        if (nums == null || nums.length < 2) {
            return new int[]{-1,-1};
        }
        target = Math.abs(target);
        int n = nums.length;

        int j = 1;
        for (int i = 0; i < n; i++) {
            j = Math.max(j, i+1);
            while (j < n && nums[j] - nums[i] < target) {
                j++;
            }
            if (j > n) {
                break;
            }
            if (nums[j] - nums[i] == target) {
                return new int[]{nums[i], nums[j]};
            }
        }
        return new int[]{-1,-1};
    }
}

Last updated