1.6 KiB
1.6 KiB
title, date, tags, categories, description, cover
| title | date | tags | categories | description | cover | ||
|---|---|---|---|---|---|---|---|
| LeetCode刷题:twoSum | 2021-10-19 18:48:41 |
|
|
LeetCode twoSum题 | 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].
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];
}
}
};
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;
}
};
// 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);
}
}
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);
}
};