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

Leetcode 1 Two Sum - 图1

Solution 2: HashMap with One Times Array Traversing

Leetcode 1 Two Sum - 图2

Implementation

Solution 1

  1. public int[] twoSum(int[] nums, int target) {
  2. HashMap < Integer, Integer > map = new HashMap < > ();
  3. int[] result = new int[2];
  4. for (int i = 0; i < nums.length; i++) {
  5. map.put(target - nums[i], i);
  6. }
  7. for (int j = 0; j < nums.length; j++) {
  8. if (map.containsKey(nums[j]) && map.get(nums[j]) != j) {
  9. result[0] = map.get(nums[j]);
  10. result[1] = j;
  11. }
  12. }
  13. return result;
  14. }

Solution 2

  1. public int[] twoSum(int[] numbers, int target) {
  2. int[] result = new int[2];
  3. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  4. for (int i = 0; i < numbers.length; i++) {
  5. if (map.containsKey(target - numbers[i])) {
  6. result[1] = i;
  7. result[0] = map.get(target - numbers[i]);
  8. return result;
  9. }
  10. map.put(numbers[i], i);
  11. }
  12. return result;
  13. }