## Algorithm problem: sum of two numbers -- JavaScript and Java implementation

A cup of green tea 2021-02-23 02:34:08
algorithm problem sum numbers javascript

Given an array of integers `nums` And a target value `target` , Find two integers in the array whose target value is sum , And return their array subscripts .

## JavaScript Realization

Used ES6 Medium `Map` object , The code is as follows ：

``````const nums = [2, 7, 11, 15],
target = 9;
function sumofTwoNumber(nums, target) {
let map = new Map();
for(let i=0; i<nums.length; i++) {
let k = target - nums[i];
if(map.has(k)) {
return [map.get(k), i]
}
map.set(nums[i], i)
}
return []
}
const res = sumofTwoNumber(nums, target);
console.log(res); // [0, 1]``````

## Java Realization

Use HashMap Realization , The code is as follows ：

``````package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
public class SumOfTwoNumberUsingHashMap {
public static List<Integer> sumOfTwoNumber(List<Integer> nums, Integer target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.size(); i++) {
int k = target - nums.get(i);
if(map.containsKey(k)) {
List<Integer> list = new ArrayList<>();
return list;
}
map.put(nums.get(i), i);
}
List<Integer> list = new ArrayList<>();
return list;
}
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();