Two Sum - Difference equals to target

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.

 Notice

It's guaranteed there is only one available solution

Example

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

该题目可以使用hashmap的方式尽心处理,也可以使用双指针的方式进行处理。使用双指针的方法需要重新设置一个类,进而定义一个带有索引和
该处数值的一个类。

java

class Pair {
    int value;
    int index;
    public Pair(int value, int index) {
        this.value = value;
        this.index = index;
    }
}
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[]{};
        }
        target = Math.abs(target);
        Pair[] p = new Pair[nums.length];
        for (int i = 0; i < nums.length; i++) {
            p[i] = new Pair(nums[i], i);
        }       
        Comparator<Pair> cmp = new Comparator<Pair>() {
            public int compare(Pair a, Pair b) {
                return a.value - b.value;
            }
        };
        Arrays.sort(p, cmp);
        int left = 0, right = 0, sum = 0;
        int[] arr = new int[2];
        while (left < nums.length && right < nums.length) {
            sum = p[right].value - p[left].value;
            if (sum == target) {
                if (left == right) {
                    right++;
                    continue;
                }
                arr[0] = p[left].index + 1;
                arr[1] = p[right].index + 1;
                break;
            } else if (sum < target) {
                right++;
            } else {
                left++;
            }
        }
        Arrays.sort(arr);
        return arr;
    }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值