doc: add twoSum problem description and solutions to the leetcode twoSum problem
This commit is contained in:
1 parent
2ca93f8043
commit
648e8b8dc6
1 file changed
+64
-1
+64
-1
@@ -7,4 +7,67 @@ categories:
|
||||
- LeetCode
|
||||
description: LeetCode twoSum题
|
||||
cover: https://upload.wikimedia.org/wikipedia/commons/0/0a/LeetCode_Logo_black_with_text.svg
|
||||
---
|
||||
---
|
||||
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.
|
||||
|
||||
Example:
|
||||
|
||||
Given nums = [2, 7, 11, 15], target = 9,
|
||||
|
||||
Because nums[0] + nums[1] = 2 + 7 = 9,
|
||||
return [0, 1].
|
||||
|
||||
```javascript
|
||||
nums = [2, 7, 11, 15];
|
||||
console.log(nums);
|
||||
|
||||
total = nums[0] + nums[1];
|
||||
console.log(total);
|
||||
|
||||
const twoSum = function (nums, target) {
|
||||
const totals = {};
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (total[nums[i]] >= 0) {
|
||||
return [total[nums[i]], i];
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
```javascript
|
||||
const twoSum = function (nums, target) {
|
||||
const comp = {};
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (comp[nums[i]] >= 0) {
|
||||
return [comp[nums[i]], i]
|
||||
}
|
||||
comp[target - nums[i]] = i;
|
||||
}
|
||||
};
|
||||
```
|
||||
```javascript
|
||||
// O(n) - One-pass Hash Table
|
||||
let twoSum = function (nums, target) {
|
||||
let map = new Map;
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
let completement = target - nums[i];
|
||||
if (map.has(complement)) {
|
||||
return [map.get(complement), i]
|
||||
}
|
||||
map.set(nums[i], i);
|
||||
}
|
||||
}
|
||||
```
|
||||
```javascript
|
||||
const twoSum = function (nums, target) {
|
||||
const map = new Map();
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
const comp = target - nums[i];
|
||||
if (map.has(comp)) {
|
||||
return [map.get(comp), i];
|
||||
}
|
||||
map.set(nums[i], i);
|
||||
}
|
||||
};
|
||||
```
|
||||
Reference in new issue
Block a user