1.two sum
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.
题意:给定一个整数数组,寻找两个整数使它们的和等于target,并且返回它们的下标。题目假定只有唯一解,因此我们不用考虑其他情况。
example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
1.1 蛮力法
蛮力法是最简单也是最耗时的算法,直接两个for循环遍历数组并和target进行比较就能解决问题
var twoSum = function(nums, target) {
var len = nums.length;
for(var i = 0;i<len;i++){
for(var j=i+1;j<len;j++){
if(nums[i] + nums[j] == target){
return [i,j];
}
}
}
}
1.2 hash 表法
时间代价是O(n*n),但这很明显不是我们想要的答案,考虑有没有一种时间代价是O(n)的算法呢?那就是Hash表。JavaScript语言没有封装hash map,但由于hash表本质上是键值对,也即是对象,所以可以构建对象hash。
/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var twoSum = function(nums, target) {
var len = nums.length;
var hash = {};
//用hash表解决方法如下
for(var i =0;i<len;i++){
var diff = target - nums[i];
if( hash[diff] !== undefined ){
return [hash[diff],i];
}
hash[nums[i]] = i;//存入nums数组的每一个数
}
};
2.two sum II–input array is sorted
Given an array of integers that is already sorted in ascending order, 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.
题意:在一个已排序的数组中找出两个数,使得他们的和等于target,返回他们的下标。且下标不从0开始计算,要求下标也排好序。
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
本题和上一道题的区别是给定的是一个已排序的数组,我们可以从两头向中间遍历。两数之和小于target,则左边的下标右移。若大于target,则右边的下标左移。因此这样用蛮力法的时间代价也是O(n)。
2.1蛮力法
/** * @param {number[]} numbers * @param {number} target * @return {number[]} */
var twoSum = function(numbers, target) {
//蛮力算法
var left=0, right=numbers.length-1;
while(numbers[left] + numbers[right] !== target){
if(numbers[left] + numbers[right] < target){
left++;
}else {
right--;
}
}
return [left+1, right+1];
};
2.2hash表法
用hash表法的过程和上一道题一样,没有变化。
/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var twoSum = function(nums, target) {
var len = nums.length;
var hash = {};
//用hash表解决方法如下
for(var i =0;i<len;i++){
var diff = target - nums[i];
if( hash[diff] !== undefined ){
return [hash[diff],i];
}
hash[nums[i]] = i;//存入nums数组的每一个数
}
};