1. Two Sum

来源:互联网 发布:淘宝联盟推广位是什么 编辑:程序博客网 时间:2024/06/06 01:21

示例

题目描述:

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

题目翻译

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

示例:

给定nums = [2,7,11,15],target = 9,因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9,返回[ 0,1 ]。

解题方案

标签: Hash Table、Array

思路:

方法一:最简单的思路是遍历数组,看数组中剩下的数里是否存在nums[j]=target-nums[i];

方法二:将数组中的数插入HashMap中,再遍历数组,看(target-nums[i])是否在HashMap中。其时间复杂度和空间复杂度都是O(n),因为Hash Table的查找时间复杂度是O(1)。

代码:

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");}
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");}
原创粉丝点击