Difficulty: Easy Total Accepted: 802.9K Total Submissions: 2.2M
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和一个目标数值target,在数组中找到两个位置,使得该位置对应的数字之和等于target的值,结果返回这两个数在数组中的位置。注意:位置下标从0开始的。
这是首先想到的方法,也是最简单直接有效的方法。遍历数组中所有两个数之和,找到等于目标值的两个数并返回数组下标即可,若没找到则抛出一个异常。
public static int[] twoSum1(int[] nums, int target){ int[] result = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; return result; } } } throw new IllegalArgumentException("No solution"); }此方法虽然可行,但是时间复杂度有点高,耗时间。
在Hash表中key存放目标值与给定数组中每个数的差值,value存放出现的位置,然后循环遍历给定数组,在Hash表中找到等于差的数,存在则取出对应的索引,保存结果并返回。
public static int[] twoSum2(int[] nums, int target){ int[] result = new int[2]; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])){ result[0] = map.get(nums[i]); result[1] = i; return result; } else map.put(target-nums[i], i); } throw new IllegalArgumentException("No solution"); }提交后AC,时间复杂度O(n),运行时间明显比方法一快很多。 看网上应该还有其他方法,但我还没有细看与测试,目前代码只是用Java来实现,等有空了再详细研究以下其他方法的思路和用其他语言实现吧。
