From e6829daa94971d9ae3c09613e6c1c510ba8bade3 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Fri, 20 Jan 2023 11:44:28 -0800 Subject: [PATCH 1/2] solve 747. Largest Number At Least Twice of Others --- 747.largest-number-at-least-twice-of-others.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 747.largest-number-at-least-twice-of-others.js 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; From 6933bbc18796459496bc6886d9caddda05db262a Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Fri, 20 Jan 2023 11:45:01 -0800 Subject: [PATCH 2/2] test function dominantIndex --- dominantIndex.test.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 dominantIndex.test.js 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); +});