I've recently gotten into Typescript and I'm solving some Leetcodes to learn.
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up totarget
.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.
Constraints:
- 2 <=
nums.length
<= 104- \$-10^9\$ <=
nums[i]
<= \$10^9\$- \$-10^9\$ <=
target
<= \$10^9\$- Only one valid answer exists.
I wrote this:
function twoSum(nums: number[], target: number): number[] {
let map: Entry[] = [];
type Entry = {
readonly index: number,
readonly value: number,
};
let result: number[] = [];
let test: any = nums.map((elem, index) => {
let map_search = map.find((entry) => entry.value === target - elem);
if(map_search) {
// contains suitable index
result.push(index, map_search.index);
} else {
let new_entry: Entry = {
index: index,
value: elem,
};
map.push(new_entry);
}
})
if(result) {
return result;
} else {
return [];
}
};
My solution works, but it feels a bit messy and inefficient in places. I feel like I'm not doing things in the proper Typescript way. Are there any suggestions for improvement?