-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 311 ms (42.48%) | Memory: 96.4 MB (44.51%) - LeetSync
- Loading branch information
1 parent
2e1540b
commit 7ef7d4d
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
28 changes: 28 additions & 0 deletions
28
2271-rearrange-array-elements-by-sign/rearrange-array-elements-by-sign.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/** | ||
* @param {number[]} nums | ||
* @return {number[]} | ||
*/ | ||
var rearrangeArray = function(nums) { | ||
let solution = new Solution(); | ||
return solution.rearrangeArray(nums); | ||
}; | ||
|
||
|
||
var Solution = function() {}; | ||
|
||
Solution.prototype.rearrangeArray = function(nums) { | ||
let ans = new Array(nums.length).fill(0); | ||
let pos = 0, neg = 1; | ||
|
||
for (let i = 0; i < nums.length; i++) { | ||
if (nums[i] > 0) { | ||
ans[pos] = nums[i]; | ||
pos += 2; | ||
} else { | ||
ans[neg] = nums[i]; | ||
neg += 2; | ||
} | ||
} | ||
|
||
return ans; | ||
}; |