diff --git a/747.largest-number-at-least-twice-of-others.js b/747.largest-number-at-least-twice-of-others.js new file mode 100644 index 00000000..9622efca --- /dev/null +++ b/747.largest-number-at-least-twice-of-others.js @@ -0,0 +1,18 @@ +/* URL of this problem + * https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ + * + * @param {number[]} nums + * @return {number} + */ + +var dominantIndex = function (nums) { + // Sort nums in a descending order + const SortedNums = [...nums].sort((a, b) => b - a); + + if (SortedNums[0] / 2 >= SortedNums[1]) { + return nums.indexOf(SortedNums[0]); + } + return -1; +}; + +module.exports = dominantIndex; diff --git a/dominantIndex.test.js b/dominantIndex.test.js new file mode 100644 index 00000000..a2027d3d --- /dev/null +++ b/dominantIndex.test.js @@ -0,0 +1,25 @@ +const dominantIndex = require("./747.largest-number-at-least-twice-of-others"); + +test("Return the index of the largest number in the array", () => { + expect(dominantIndex([3, 6, 1, 0])).toBe(1); +}); + +test("Return -1 if the largest integer is not at least twice as much as every other number in the array", () => { + expect(dominantIndex([1, 2, 3, 4])).toBe(-1); +}); + +test("Return -1 if the array is empty", () => { + expect(dominantIndex([])).toBe(-1); +}); + +test("Return -1 if the array is empty", () => { + expect(dominantIndex([])).toBe(-1); +}); + +test("Return the index of Infinity in the array if there is", () => { + expect(dominantIndex([3, 6, 1, 0, Infinity])).toBe(4); +}); + +test("Return the index of the largest number in the array with -Infinity", () => { + expect(dominantIndex([3, 6, 1, 0, -Infinity])).toBe(1); +});