leetcode 1 Two Sum Java & JavaScript解法

2018-03-01 11:14:13来源:segmentfault作者:soleil阿璐人点击

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

HashMap remain用来存储，每一个元素和目标元素的差值和这个元素的位置。这样的话，如果我们后续遍历到的元素刚好等于这个差值，就说明这两个元素加和刚好等于目标和。

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

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