LeetCode之Tow Sum
Problem:
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.
给你一个整数数组,返回两个数组元素的下标,这两个数组元素相加得到一个特殊的数字target。
你可以假定每次输入只有一个正确答案,但你不能使用同一个元素两次以上。
Solution
--1--
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[j] == target - nums[i]) { return new int[] { i, j }; } } } throw new IllegalArgumentException("No two sum solution"); }
new Int[] = {} --- Java数组当对象new出来
IllegalArgumentException --- 参数异常
--2--
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"); }
map.containKey --- 判断map是否含有该值