File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 591
591
778|[ Swim in Rising Water] ( ./0778-swim-in-rising-water.js ) |Hard|
592
592
779|[ K-th Symbol in Grammar] ( ./0779-k-th-symbol-in-grammar.js ) |Medium|
593
593
780|[ Reaching Points] ( ./0780-reaching-points.js ) |Hard|
594
+ 781|[ Rabbits in Forest] ( ./0781-rabbits-in-forest.js ) |Medium|
594
595
783|[ Minimum Distance Between BST Nodes] ( ./0783-minimum-distance-between-bst-nodes.js ) |Easy|
595
596
784|[ Letter Case Permutation] ( ./0784-letter-case-permutation.js ) |Medium|
596
597
790|[ Domino and Tromino Tiling] ( ./0790-domino-and-tromino-tiling.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 781. Rabbits in Forest
3
+ * https://leetcode.com/problems/rabbits-in-forest/
4
+ * Difficulty: Medium
5
+ *
6
+ * There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have
7
+ * the same color as you?" and collected the answers in an integer array answers where answers[i]
8
+ * is the answer of the ith rabbit.
9
+ *
10
+ * Given the array answers, return the minimum number of rabbits that could be in the forest.
11
+ */
12
+
13
+ /**
14
+ * @param {number[] } answers
15
+ * @return {number }
16
+ */
17
+ var numRabbits = function ( answers ) {
18
+ const colorGroups = { } ;
19
+ let totalRabbits = 0 ;
20
+
21
+ for ( const answer of answers ) {
22
+ if ( answer === 0 ) {
23
+ totalRabbits ++ ;
24
+ continue ;
25
+ }
26
+
27
+ if ( ! colorGroups [ answer ] || colorGroups [ answer ] === 0 ) {
28
+ totalRabbits += answer + 1 ;
29
+ colorGroups [ answer ] = answer ;
30
+ } else {
31
+ colorGroups [ answer ] -- ;
32
+ }
33
+ }
34
+
35
+ return totalRabbits ;
36
+ } ;
You can’t perform that action at this time.
0 commit comments