import java.util.HashMap; import java.util.Map; /** * 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。 * 你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。 * <p> * 示例: * 給定 nums = [2, 7, 11, 15], target = 9 * 由於 nums[0] + nums[1] = 2 + 7 = 9 * 因此返回 [0, 1] * 2019/7/21 */ public class No1 { public static void main(String[] args) { int[] nums = {1, 2, 3, 4, 5}; int target = 6; int[] position = new No1().solution1(nums, target); for (int x : position ) { System.out.print(x + " "); } } private int[] solution(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if ((i != j) && (target - nums[i] == nums[j])) { return new int[]{i, j}; } } } return null; } private int[] solution1(int[] nums, int target) { Map<Integer, Integer> numMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { numMap.put(nums[i], i); } for (int j = 0; j < nums.length; j++) { if (numMap.containsKey(target - nums[j]) && numMap.get(target - nums[j]) != j) { return new int[]{j, numMap.get(target - nums[j])}; } } return null; } private int[] solution2(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"); } }