From 0c9cb71312bb27988b6162fa870088e2fd674654 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Mon, 2 Jan 2023 19:49:13 -0800 Subject: [PATCH 1/2] solve 2229. Check if an Array Is Consecutive --- 2229.check-if-an-array-is-consecutive.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 2229.check-if-an-array-is-consecutive.js diff --git a/2229.check-if-an-array-is-consecutive.js b/2229.check-if-an-array-is-consecutive.js new file mode 100644 index 00000000..3ec1aa5d --- /dev/null +++ b/2229.check-if-an-array-is-consecutive.js @@ -0,0 +1,21 @@ +/* URL of this problem + * https://leetcode.com/problems/check-if-an-array-is-consecutive/description/ + * + * @param {number[]} nums + * @return {boolean} + */ + +var isConsecutive = function(nums) { + const SortedNums = [...nums].sort((a, b) => a - b); + const RangeStart = Math.min(...nums); + const RangeEnd = RangeStart + nums.length - 1; + const RangeNums = []; + + for (let i = RangeStart; i <= RangeEnd; i++) { + RangeNums.push(i); + } + + return SortedNums.join("") === RangeNums.join(""); +}; + +module.exports = isConsecutive; \ No newline at end of file From 34b74a1941e1a715157e8b5ba3c17847a23f41e9 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Mon, 2 Jan 2023 19:49:46 -0800 Subject: [PATCH 2/2] test function isConsecutive --- isConsecutive.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 isConsecutive.test.js diff --git a/isConsecutive.test.js b/isConsecutive.test.js new file mode 100644 index 00000000..5182d23b --- /dev/null +++ b/isConsecutive.test.js @@ -0,0 +1,13 @@ +const isConsecutive = require("./2229.check-if-an-array-is-consecutive"); + +test("Return true if the input nums contains all the integers in the range", () => { + expect(isConsecutive([1,3,4,2])).toBeTruthy(); +}); + +test("Return false if the input nums misses any integer in the range", () => { + expect(isConsecutive([1,3])).toBeFalsy(); +}); + +test("Return false if the input nums contains Infinity", () => { + expect(isConsecutive([1,3,4,2,Infinity])).toBeFalsy(); +}); \ No newline at end of file