-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2149-rearrange-array-elements-by-sign.js
More file actions
33 lines (30 loc) · 1.01 KB
/
2149-rearrange-array-elements-by-sign.js
File metadata and controls
33 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 2149. Rearrange Array Elements by Sign
* https://leetcode.com/problems/rearrange-array-elements-by-sign/
* Difficulty: Medium
*
* You are given a 0-indexed integer array nums of even length consisting of an equal number
* of positive and negative integers.
*
* You should return the array of nums such that the the array follows the given conditions:
* 1. Every consecutive pair of integers have opposite signs.
* 2. For all integers with the same sign, the order in which they were present in nums is
* preserved.
* 3. The rearranged array begins with a positive integer.
*
* Return the modified array after rearranging the elements to satisfy the aforementioned
* conditions.
*/
/**
* @param {number[]} nums
* @return {number[]}
*/
var rearrangeArray = function(nums) {
const positives = nums.filter(num => num > 0);
const negatives = nums.filter(num => num < 0);
const result = [];
for (let i = 0; i < positives.length; i++) {
result.push(positives[i], negatives[i]);
}
return result;
};