1. Two Sum (E)

Two Sum (E)

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].

题意

给定一个数组和一个指定值target,要求在数组中找到两个值,使其和正好等于target,并返回这两个值所对应的下标。保证仅有唯一的组合,且不能使用同一个值两次。

思路

常规方法暴力枚举即可,复杂度为O(N2)O(N^2)O(N2)
比较快速的方法是使用散列来处理。注意到最后要求返回下标而不是具体的值,使用HashMap<Integer, Integer>来保存<具体值, 原数组中的下标>,遍历数组进行如下操作:对于每一个数,先查找散列中是否已有对应的值,有则直接返回;没有则将该数及其对应下标存入散列。复杂度为O(N)O(N)O(N)


代码实现

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashTable = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int n = target - nums[i];
            // 先查找散列中是否已有对应的值
            if (hashTable.containsKey(n)) {
                return new int[]{hashTable.get(n), i};
            }
            // 不存在则再存入散列
            hashTable.put(nums[i], i);
        }
        return new int[]{};
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值