-
Notifications
You must be signed in to change notification settings - Fork 187
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #833 from 0xff-dev/846
Add solution and test-cases for problem 846
- Loading branch information
Showing
3 changed files
with
93 additions
and
27 deletions.
There are no files selected for viewing
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
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 |
---|---|---|
@@ -1,5 +1,73 @@ | ||
package Solution | ||
|
||
func Solution(x bool) bool { | ||
return x | ||
import ( | ||
"sort" | ||
) | ||
|
||
func Solution(hand []int, groupSize int) bool { | ||
l := len(hand) | ||
if l%groupSize != 0 { | ||
return false | ||
} | ||
if groupSize == 1 { | ||
return true | ||
} | ||
|
||
keys := make([]int, 0) | ||
keyCount := make(map[int]int) | ||
for _, n := range hand { | ||
keyCount[n]++ | ||
if keyCount[n] == 1 { | ||
keys = append(keys, n) | ||
} | ||
} | ||
sort.Ints(keys) | ||
|
||
idx := 1 | ||
count := keyCount[keys[0]] | ||
nextIdx := -1 | ||
keyCount[keys[0]] = 0 | ||
used := 1 | ||
l -= count | ||
|
||
for idx < len(keys) { | ||
if keys[idx]-keys[idx-1] != 1 { | ||
return false | ||
} | ||
keyCount[keys[idx]] -= count | ||
l -= count | ||
used++ | ||
if keyCount[keys[idx]] < 0 { | ||
return false | ||
} | ||
if keyCount[keys[idx]] > 0 && nextIdx == -1 { | ||
nextIdx = idx | ||
} | ||
|
||
if used != groupSize { | ||
idx++ | ||
continue | ||
} | ||
if nextIdx == -1 { | ||
if idx == len(keys)-1 { | ||
break | ||
} | ||
idx++ | ||
count = keyCount[keys[idx]] | ||
nextIdx = -1 | ||
keyCount[keys[idx]] = 0 | ||
l -= count | ||
used = 1 | ||
idx++ | ||
continue | ||
} | ||
|
||
idx = nextIdx + 1 | ||
count = keyCount[keys[nextIdx]] | ||
keyCount[keys[nextIdx]] = 0 | ||
nextIdx = -1 | ||
l -= count | ||
used = 1 | ||
} | ||
return l == 0 && used == groupSize | ||
} |
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