-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path001-twoSum.js
More file actions
61 lines (54 loc) · 1.81 KB
/
001-twoSum.js
File metadata and controls
61 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
* 示例:
* 给定 nums = [2, 7, 11, 15], target = 9
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
**/
// solution1:
var twoSum = function(nums, target) {
// Map 对象保存键值对
const map = new Map()
for(let i = 0; i < nums.length; i++){
if (map.has(target - nums[i])){
console.log(map.get(target - nums[i]));
// get返回某个 Map 对象中的一个指定元素。
return [ map.get(target - nums[i]), i ]
}
// Set对象是值的集合,你可以按照插入的顺序迭代它的元素。
// Set中的元素只会出现一次,即 Set 中的元素是唯一的。
map.set(nums[i], i)
}
};
// solution2:
var twoSum = function (numbers, target) {
let map = {};
for (let i = 0; i < numbers.length; i++) {
let n = numbers[i];
if (map[target - n] !== undefined) {
return [map[target - n], i];
} else {
map[n] = i;
}
}
};
// solution3:
var twoSum = function(nums, target) {
var tempArr = [];
for (var i = 0; i < nums.length; i++) {
var temp = target - nums[i];
// lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,
// 在一个字符串中的指定位置从后向前搜索。
var index = tempArr.lastIndexOf(temp);
console.log('i' + i)
console.log('index' + index)
if (index !== -1) {
return [index, i];
}
tempArr.push(nums[i]);
console.log('tempArr' + tempArr);
}
return null;
}
// QA: 如果不止对应一种答案呢?