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方法的意义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值