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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章