MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/easy/_0001/Solution.java:14–45  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/04/21 desc :

Source from the content-addressed store, hash-verified

12 * </pre>
13 */
14public class Solution {
15// public int[] twoSum(int[] nums, int target) {
16// for (int i = 0; i < nums.length; ++i) {
17// for (int j = i + 1; j < nums.length; ++j) {
18// if (nums[i] + nums[j] == target) {
19// return new int[]{i, j};
20// }
21// }
22// }
23// return null;
24// }
25
26 public int[] twoSum(int[] nums, int target) {
27 int len = nums.length;
28 HashMap<Integer, Integer> map = new HashMap<>();
29 for (int i = 0; i < len; ++i) {
30 final Integer value = map.get(nums[i]);
31 if (value != null) {
32 return new int[] { value, i };
33 }
34 map.put(target - nums[i], i);
35 }
36 return null;
37 }
38
39 public static void main(String[] args) {
40 Solution solution = new Solution();
41 int[] nums = new int[]{2, 7, 11, 15};
42 int target = 9;
43 System.out.println(Arrays.toString(solution.twoSum(nums, target)));
44 }
45}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected