From de59fad886965184d116a1a2653a17d1d3a05ad8 Mon Sep 17 00:00:00 2001 From: Aadil <77232799+aadil42@users.noreply.github.com> Date: Tue, 20 Jun 2023 21:12:38 +0530 Subject: [PATCH] Create 1968-array-with-elements-not-equal-to-average-of-neighbors.js Solved array-with-elements-not-equal-to-average-of-neighbors in JS. --- ...ments-not-equal-to-average-of-neighbors.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js diff --git a/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js b/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js new file mode 100644 index 000000000..dc1975f4d --- /dev/null +++ b/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js @@ -0,0 +1,25 @@ +/** + * Two Pointers + * https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ + * + * Time O(n*log(n)) | Space O(n) + * @param {number[]} nums + * @return {number[]} + */ + var rearrangeArray = function(nums) { + nums.sort((a,b) => a-b); + + let midPointer = Math.ceil(nums.length / 2); + let beginingPointer = 1; + + while(midPointer < nums.length) { + swap(midPointer, beginingPointer, nums); + midPointer++; + beginingPointer += 2 + } + return nums; + }; + +var swap = function(i,j,nums) { + [nums[i], nums[j]] = [nums[j], nums[i]]; +}