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


代码实现

Java

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[]{};
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  let map = new Map()
  for (let i in nums) {
    if (map.has(target - nums[i])) {
      return [map.get(target - nums[i]), i]
    }
    map.set(nums[i], i)
  }
}
原文地址:https://www.cnblogs.com/mapoos/p/13130220.html