diff --git a/DIRECTORY.md b/DIRECTORY.md index a32addb9de..b1ddcf9c09 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -57,6 +57,7 @@ * [LocalMaximomPoint](Data-Structures/Array/LocalMaximomPoint.js) * [NumberOfLocalMaximumPoints](Data-Structures/Array/NumberOfLocalMaximumPoints.js) * [QuickSelect](Data-Structures/Array/QuickSelect.js) + * [TwoSum](Data-Structures/Array/TwoSum.js) * **Graph** * [Graph](Data-Structures/Graph/Graph.js) * [Graph2](Data-Structures/Graph/Graph2.js) diff --git a/Data-Structures/Array/TwoSum.js b/Data-Structures/Array/TwoSum.js new file mode 100644 index 0000000000..e72af9c58d --- /dev/null +++ b/Data-Structures/Array/TwoSum.js @@ -0,0 +1,20 @@ +/** + * @function TwoSum + * @see https://leetcode.com/problems/two-sum/ + * @description Given an array of integers, returns 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. This is a basic brute force approach. + * @param {Array} nums - array of integers. + * @param {number} target - target integer. + * @returns {Array} Array of the indices of the two numbers whose sum equals the target + * @example Given nums = [2, 7, 11, 15], target = 9; return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9 + * @complexity: O(n^2) + */ +const TwoSum = (nums, target) => { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] === target) { + return [i, j] + } + } + } +} +export { TwoSum } diff --git a/Data-Structures/Array/test/TwoSum.test.js b/Data-Structures/Array/test/TwoSum.test.js new file mode 100644 index 0000000000..4b0f40db58 --- /dev/null +++ b/Data-Structures/Array/test/TwoSum.test.js @@ -0,0 +1,9 @@ +import { TwoSum } from '../TwoSum' + +test('TwoSum tests', () => { + expect(TwoSum([2, 7, 11, 15], 9)).toEqual([0, 1]) + expect(TwoSum([2, 7, 11, 15, 6], 8)).toEqual([0, 4]) + expect(TwoSum([1, 0, 5, 7, 3, 4], 6)).toEqual([0, 2]) + expect(TwoSum([0, 8, 3, 1, 2, 7, 3], 6)).toEqual([2, 6]) + expect(TwoSum([0, 5, 4, 2, 6, 7, 9, 1], 3)).toEqual([3, 7]) +})