leetcode (1) Two Sum js代码实现
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var temp = nums.slice(0);
nums = nums.sort(function(a,b){return a-b;});
var i = 0;
var j = nums.length - 1;
while(nums[i] + nums[j] != target){
if(nums[i] + nums[j] > target){
j--;
}else{
i++;
}
}
console.log(i);
console.log(j);
i = temp.indexOf(nums[i]);
console.log(i);
j = temp.lastIndexOf(nums[j]);
i++;j++;
var index = new Array(i, j);
console.log(temp);
console.log(nums);
console.log(index);
index = index.sort(function(a,b){return a-b;});
return index;
};
这道题目的主要思路:如果刚拿到题目的时候,可能想要会暴力穷举直接过了这道题,然而这样做性能太差无法通过,我们需要更加优秀的算法,那么就很容易想到现将给出的数组进行排序,从i=0和j=end开始计算两数相加之和,如果得到的sum大于目标值target,j向左移动,反之,i向右移动,这样的方法找到加数后再去原数组中找到两个数的数组下标就可以了
注意:这里用到深拷贝的方法,浅拷贝是引用,深拷贝是复制
同样也应该注意的是sort方法的意义
还没有评论,来说两句吧...