December 12, 2023

Viiisit [LeetCode] - 1. Two Sum

#php#javascript#ruby

keep learning, keep coding!

Problem - Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

翻譯蒟蒻

給定一個整數陣列 nums 和一個目標整數 target,找出陣列中兩個數字的索引,使和等於 target。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let score = {}
for (let i = 0; i < nums.length; i++) {
let num = nums[i]
let diff = target - num
if (score[diff] !== undefined) {
return [score[diff], i]
}
score[num] = i
}
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
def two_sum(nums, target)
score = {}
nums.each_with_index do |num, index|
if score[target - num]
return [score[target - num], index]
else
score[num] = index
end
end

[]
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
function twoSum($nums, $target) {
$score = [];
foreach ($nums as $key => $value) {
$score[$value] = $key;
}
foreach ($nums as $key => $value) {
$diff = $target - $value;
if (isset($score[$diff]) && $score[$diff] != $key) {
return [$key, $score[$diff]];
}
}
return [];
}

LeetCode 傳送門 - Two Sum