|
1 | | -package com.medium; |
2 | | - |
3 | | -/* |
4 | | -No.1 Two Sum |
5 | | -Given an array of integers, find two numbers such that they add up to a specific target number. |
6 | | -
|
7 | | -The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. |
8 | | -
|
9 | | -You may assume that each input would have exactly one solution. |
10 | | -
|
11 | | -Input: numbers={2, 7, 11, 15}, target=9 |
12 | | -Output: index1=1, index2=2 |
13 | | - */ |
14 | | - |
15 | | - |
16 | | -import java.util.Arrays; |
17 | 1 | import java.util.HashMap; |
18 | 2 |
|
19 | | -/** |
20 | | - * author : quantin |
21 | | - * date : 15/7/18 |
22 | | - */ |
23 | | -public class TwoSum_1 { |
24 | | - public static int[] twoSum(int[] nums, int target) { |
25 | | - HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); |
26 | | - int[] result = new int[2]; |
27 | | - |
28 | | - for (int i = 0; i < nums.length; i++) { |
29 | | - if (map.containsKey(nums[i])) { |
30 | | - int value = map.get(nums[i]); |
31 | | - result[0] = value + 1; |
32 | | - result[1] = i + 1; |
33 | | - break; |
34 | | - } |
35 | | - else |
36 | | - map.put(target - nums[i], i); |
37 | | - } |
38 | | - |
39 | | - return result; |
40 | | - } |
41 | | - |
42 | | - public static void main(String[] args) { |
43 | | - int[] testNums = {-1, -2, -3, -4, -5}; |
44 | | - int target = -8; |
45 | | - |
46 | | - int[] result = twoSum(testNums, target); |
47 | | - |
48 | | - System.out.println(result[0] + " " + result[1]); |
49 | | - } |
| 3 | +public class Solution { |
| 4 | + public int[] twoSum(int[] nums, int target) { |
| 5 | + HashMap<Integer, Integer> map = new HashMap<>(); //diamond grammar |
| 6 | + for (int i = 0; i < nums.length; i++) { |
| 7 | + if (map.get(nums[i]) != null) { |
| 8 | + return new int[]{map.get(nums[i]), i + 1}; //anonymous array |
| 9 | + } |
| 10 | + map.put(target - nums[i], i + 1); |
| 11 | + } |
| 12 | + return null; |
| 13 | + } |
50 | 14 | } |
| 15 | +// Can we make code cleaner ? |
0 commit comments