|
| 1 | +package cn.byhieg.arithmetic; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by weizhaoquan on 2019/05/09. |
| 8 | + */ |
| 9 | +public class TwoSum { |
| 10 | + public static int[] twoSum1(int[] nums, int target) { |
| 11 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 12 | + for(int i = 0; i < nums.length; i++) { |
| 13 | + map.put(nums[i], i); |
| 14 | + } |
| 15 | + for(int i = 0; i < nums.length; i++){ |
| 16 | + int val = target - nums[i]; |
| 17 | + if(map.containsKey(val) && map.get(val) != i){ |
| 18 | + return new int[]{i, map.get(val)}; |
| 19 | + } |
| 20 | + } |
| 21 | + throw new RuntimeException("No such solution!"); |
| 22 | + } |
| 23 | + public static int[] twoSum2(int[] nums, int target) { |
| 24 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 25 | + for(int i = 0; i < nums.length; i++){ |
| 26 | + int val = target - nums[i]; |
| 27 | + if(map.containsKey(val)) {// 肯定不会map.get(val) == i |
| 28 | + return new int[]{i, map.get(val)}; |
| 29 | + } |
| 30 | + map.put(nums[i], i); |
| 31 | + } |
| 32 | + throw new RuntimeException("No such solution!"); |
| 33 | + } |
| 34 | + |
| 35 | + public static void main(String[] args) { |
| 36 | + int[] nums = {2,7,11,15}; |
| 37 | + int taget = 9; |
| 38 | + int[] ints = twoSum1( nums, taget ); |
| 39 | + System.out.printf( Arrays.toString(ints) ); |
| 40 | + } |
| 41 | +} |
0 commit comments