題目描述:數組
給定一個整數數組 nums
和一個目標值 target
,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。spa
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。code
示例:blog
給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
方法一:get
public static int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) { return new int[]{-1, -1}; } int size = nums.length; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { int sum = nums[i] + nums[j]; if (sum == target) { return new int[]{i, j}; } } } return new int[]{-1, -1}; }
方法二:io
public int[] twoSum_2(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"); }