Leetcode: 1. Two Sum

1. Two Sum

Easy

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法1:排序+两头夹击

题中没说所给数组一定是有序的,所以我们假设数组是非有序的。

1. 对数组从小到大排序,可用快排算法
2. 数组开头结尾各设一指针即为 l 和 r
3. 将l和r所指向的数值相加得到sum,并与target做对比
4. 如果sum > target,说明r所指向的数值过大,所以r左移一步;继续循环;
    如果sum < target,说明l所指向的数值过小,所以需要右移一步;继续循环;
    如果sum == target,说明已经找到了能够凑成target的两个数值;停止循环
5. 至此,我们虽然虽然找到了这两个数值,但是因为之前对数值重排序过了,所以现在的数值所在索引位置未必是之前原数组的。因此我们需要对原数组遍历,找到这两个数值对应的索引。这个操作用一次循环即可。

public static int[] twoSum(int[] nums, int target) {
        int[] copy = Arrays.copyOfRange(nums, 0, nums.length);
        Arrays.sort(nums);

        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum < target) {
                left++;
            } else if (sum > target) {
                right--;
            } else {
                break;
            }
        }

        int l = -1, r = -1;
        for (int i = 0; i < copy.length; i++) {
            if (copy[i] == nums[left] && l == -1) {
                l = i;
            } else if (copy[i] == nums[right]) {
                r = i;
            }

        }

        return new int[] { l, r };
}

解法2:HashMap记录索引位

因为题中明确说了仅有两个数字相加可组成target。说明如果真的存在这两个数,那么只要数组中存在其中一个数,那么另一个数就必定存在在数组中剩下的几个数中。所以我们可以通过一个hashmap记录每个数值在数组中的索引位置。Key为数值本身,value为索引位。这样我们可以依次遍历数组中的值,并假设当前值为组成target的其中一个值,然后判断map中是否存在另一个数(target-当前值);如果存在,那么返回map中相应的key对应的value即可。

public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
}

解法3:HashMap记录索引位(优化版)

根据解法2,其实无需一开始就遍历一次数组将数字依次存入map。我们可以在遍历判断的同时去初始化map。理由是如果target=a+b,那么及时在遍历a的时候b还没有被存入map中,那么在遍历到b的时候a也必然会在此之前被存入了map。

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yexianyi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值