Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5.7k
Two sum#1226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
base:master
Are you sure you want to change the base?
Uh oh!
There was an error while loading.Please reload this page.
Two sum#1226
Changes fromall commits
bb3bc98
7791b7a
424b235
c7b07ce
22f1ccb
cfa17fd
e847c45
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. That's a pretty naive implementation with a runtime of O(n²). Please document this in the JSDoc comment. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Please seethe docs and use the proper | ||
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 } |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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]) | ||
}) |