Question Link
https://leetcode.com/problems/two-sum/
Question Description
Find two value in array that sum up to be target. There is only one solution.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Simulation
Solution 1: HashMap with Two Times Array Traversing
Solution 2: HashMap with One Times Array Traversing
Implementation
Solution 1
public int[] twoSum(int[] nums, int target) {HashMap < Integer, Integer > map = new HashMap < > ();int[] result = new int[2];for (int i = 0; i < nums.length; i++) {map.put(target - nums[i], i);}for (int j = 0; j < nums.length; j++) {if (map.containsKey(nums[j]) && map.get(nums[j]) != j) {result[0] = map.get(nums[j]);result[1] = j;}}return result;}
Solution 2
public int[] twoSum(int[] numbers, int target) {int[] result = new int[2];Map<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < numbers.length; i++) {if (map.containsKey(target - numbers[i])) {result[1] = i;result[0] = map.get(target - numbers[i]);return result;}map.put(numbers[i], i);}return result;}
