Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 773d464

Browse files
committed
Add solution #912
1 parent 303dae1 commit 773d464

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

0912-sort-an-array.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 912. Sort an Array
3+
* https://leetcode.com/problems/sort-an-array/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers nums, sort the array in ascending order and return it.
7+
*
8+
* You must solve the problem without using any built-in functions in O(nlog(n)) time
9+
* complexity and with the smallest space complexity possible.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @return {number[]}
15+
*/
16+
var sortArray = function(nums) {
17+
if (nums.length <= 1) {
18+
return nums;
19+
}
20+
21+
const min = Math.min(...nums);
22+
const max = Math.max(...nums);
23+
const count = new Array(max - min + 1).fill(0);
24+
25+
nums.forEach(n => count[n - min]++);
26+
27+
for (let i = 0, j = 0; i < count.length; i++) {
28+
while (count[i]-- > 0) {
29+
nums[j++] = i + min;
30+
}
31+
}
32+
33+
return nums;
34+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@
252252
890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium|
253253
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
254254
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
255+
912|[Sort an Array](./0912-sort-an-array.js)|Medium|
255256
914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|
256257
916|[Word Subsets](./0916-word-subsets.js)|Medium|
257258
922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy|

0 commit comments

Comments
 (0)