1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import com.alibaba.fastjson.JSON; import java.util.HashMap; import java.util.Map;
class Solution {
public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{2, 7, 11, 15}; System.out.println(JSON.toJSONString(s.twoSum1(nums, 9))); System.out.println(JSON.toJSONString(s.twoSum2(nums, 9))); System.out.println(JSON.toJSONString(s.twoSum3(nums, 9))); }
public int[] twoSum1(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(String.format("can not calc twoSum of %s in %s", target, JSON.toJSONString(nums))); }
public int[] twoSum2(int[] nums, int target) { Map<Integer, Integer> numsMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { numsMap.put(nums[i], i); }
for (int j = 0; j < nums.length; j++) { int left = target - nums[j]; if (numsMap.containsKey(left) && numsMap.get(left) != j) { return new int[]{numsMap.get(left), j}; } } throw new IllegalArgumentException(String.format("can not calc twoSum of %s in %s", target, JSON.toJSONString(nums))); }
public int[] twoSum3(int[] nums, int target) { Map<Integer, Integer> numsMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int left = target - nums[i]; if (numsMap.containsKey(left)) { return new int[]{numsMap.get(left), i}; } numsMap.put(nums[i], i); } throw new IllegalArgumentException(String.format("can not calc twoSum of %s in %s", target, JSON.toJSONString(nums))); } }
|