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; };