leetcode 1. Two Sum

33 篇文章 0 订阅
30 篇文章 0 订阅

1. Two Sum

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].
tag: array, hash table

method 1

two-pass hash table 第一边遍历,将每一个数放进map中,第二次遍历时,遍历map中是否存在target-nums[i]有就取索引直接返回

public int[] twoSum(int[] nums, int target) {
    Set<Integer> set = new HashSet<>();
    int[] res = new int[2];
    int anotherNum = 0;
    for (int i = 0; i < nums.length; i++) {
        if (set.contains(target-nums[i])){
            res[1] = i;
            anotherNum = target-nums[i];
            break;
        }
        set.add(nums[i]);
    }

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == anotherNum){
            res[0] = i;
            break;
        }
    }

    return res;
}
method 2

one-pass hash table, 其实一次遍历就够,每次遍历的时候检查map中是否有target-nums[i]的数,没有就放进map中,总会找到的

public int[] twoSum2(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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值