Skip to content

Commit d010375

Browse files
committed
Add solution #659
1 parent cc982b0 commit d010375

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,7 @@
496496
655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium|
497497
657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy|
498498
658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium|
499+
659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium|
499500
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
500501
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
501502
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 659. Split Array into Consecutive Subsequences
3+
* https://leetcode.com/problems/split-array-into-consecutive-subsequences/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums that is sorted in non-decreasing order.
7+
*
8+
* Determine if it is possible to split nums into one or more subsequences such that both of the
9+
* following conditions are true:
10+
* - Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more
11+
* than the previous integer).
12+
* - All subsequences have a length of 3 or more.
13+
*
14+
* Return true if you can split nums according to the above conditions, or false otherwise.
15+
*
16+
* A subsequence of an array is a new array that is formed from the original array by deleting some
17+
* (can be none) of the elements without disturbing the relative positions of the remaining
18+
* elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).
19+
*/
20+
21+
/**
22+
* @param {number[]} nums
23+
* @return {boolean}
24+
*/
25+
var isPossible = function(nums) {
26+
const map = new Map();
27+
const map2 = new Map();
28+
29+
for (const n of nums) {
30+
map.set(n, (map.get(n) || 0) + 1);
31+
}
32+
33+
for (const n of nums) {
34+
if (map.get(n) === 0) continue;
35+
36+
if ((map2.get(n) || 0) > 0) {
37+
map2.set(n, map2.get(n) - 1);
38+
map.set(n, map.get(n) - 1);
39+
map2.set(n + 1, (map2.get(n + 1) || 0) + 1);
40+
} else if ((map.get(n) || 0) > 0 && (map.get(n + 1) || 0) > 0 && (map.get(n + 2) || 0) > 0) {
41+
map.set(n, map.get(n) - 1);
42+
map.set(n + 1, map.get(n + 1) - 1);
43+
map.set(n + 2, map.get(n + 2) - 1);
44+
map2.set(n + 3, (map2.get(n + 3) || 0) + 1);
45+
} else {
46+
return false;
47+
}
48+
}
49+
50+
return true;
51+
};

0 commit comments

Comments
 (0)