77 lines
1.7 KiB
Markdown
77 lines
1.7 KiB
Markdown
---
|
|
title: LeetCode刷题:twoSum
|
|
tags:
|
|
- LeetCode
|
|
categories:
|
|
- LeetCode
|
|
description: LeetCode twoSum题
|
|
cover: >-
|
|
https://upload.wikimedia.org/wikipedia/commons/1/19/LeetCode_logo_black.png
|
|
top_img: >-
|
|
https://upload.wikimedia.org/wikipedia/commons/1/19/LeetCode_logo_black.png
|
|
abbrlink: ce131649
|
|
date: 2021-10-19 18:48:41
|
|
---
|
|
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);
|
|
}
|
|
};
|
|
``` |