Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix:#758 Average Median code optimised #1380

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions Maths/AverageMedian.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,14 @@
*/

const averageMedian = (sourceArrayOfNumbers) => {
let numbers = [...sourceArrayOfNumbers]
let median = 0
const numbers = [...sourceArrayOfNumbers].sort(sortNumbers)
const numLength = numbers.length
numbers = numbers.sort(sortNumbers)

if (numLength % 2 === 0) {
median = (numbers[numLength / 2 - 1] + numbers[numLength / 2]) / 2
} else {
median = numbers[(numLength - 1) / 2]
}

return median
return (numbers[numLength / 2 - 1] + numbers[numLength / 2]) / 2
} else return numbers[Math.floor(numLength / 2)]
}

const sortNumbers = (num1, num2) => {
return num1 - num2
}
const sortNumbers = (num1, num2) => num1 - num2

export { averageMedian }
23 changes: 23 additions & 0 deletions Maths/TwoSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
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].
return [0, 1].
*/

const TwoSum = (nums, target) => {
const numIndicesMap = {}
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i]
if (complement in numIndicesMap) return [numIndicesMap[complement], i]
numIndicesMap[nums[i]] = i
}
return []
}
export { TwoSum }
18 changes: 18 additions & 0 deletions Maths/test/TwoSum.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TwoSum } from '../TwoSum.js'

describe('Two Sum', () => {
it('Should find the indices of two numbers that add up to the target', () => {
expect(TwoSum([2, 7, 11, 15], 9)).toEqual([0, 1])
expect(TwoSum([15, 2, 11, 7], 13)).toEqual([1, 2])
expect(TwoSum([2, 7, 11, 15], 17)).toEqual([0, 3])
expect(TwoSum([7, 15, 11, 2], 18)).toEqual([0, 2])
expect(TwoSum([2, 7, 11, 15], 26)).toEqual([2, 3])
expect(TwoSum([2, 7, 11, 15], 8)).toEqual([])
expect(
TwoSum(
[...Array(10).keys()].map((i) => 3 * i),
19
)
).toEqual([])
})
})