Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.题目的意思是,输入一个整数数组和一个目标和,让咱们找整数数组中的两个元素,使他们的加和恰好等于目标和。返回这两个元素的位置。每一个输入都有且仅有一组知足条件的元素。javascript
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].java
public int[] twoSum(int[] nums, int target) { int[] res = {-1,-1}; HashMap<Integer,Integer> remain = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(remain.containsKey(nums[i])){ res[0] = remain.get(nums[i]); res[1] = i; return res; }else{ remain.put(target-nums[i], i); } } return res; }
var twoSum = function(nums, target) { var res = new Array; for(let i=0;i<nums.length-1;i++){ let temp = target - nums[i]; for(let j = i+1;j<nums.length;j++){ if(temp == nums[j]){ res[0] = i; res[1] = j; return res; } } } };
var twoSum = function(nums, target) { var ans = []; var exist = {}; for (var i = 0; i < nums.length; i++){ if (typeof(exist[target-nums[i]]) !== 'undefined'){ ans.push(exist[target-nums[i]]); ans.push(i); } exist[nums[i]] = i; } return ans; };