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 thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解题思路:1.最容易想到的,莫过于构建两个循环,一组一组的去验证,此时算法复杂度为O(n2)。
public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j) == target { return new int[] { i, j }; } } } throw new IllegalArgumentException("No two sum solution"); }2.用jave,当我们在表中迭代并插入元素时,我们还会回顾一下,看看当前元素的补充是否已经存在于表中。如果存在,我们已经找到了解决方案,并立即返回。此时算法复杂度为 O(n)。
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"); }