diff --git a/solution/0800-0899/0846.Hand of Straights/README.md b/solution/0800-0899/0846.Hand of Straights/README.md index 014f8d42ac3ef..0f534a822da38 100644 --- a/solution/0800-0899/0846.Hand of Straights/README.md +++ b/solution/0800-0899/0846.Hand of Straights/README.md @@ -65,7 +65,33 @@ ```java - +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : hand) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + groupSize; i++) { + if (!mp.containsKey(i)) { + return false; + } + int time = mp.get(i); + if (time == 1) { + mp.remove(i); + } else { + mp.replace(i, time - 1); + } + } + } + return true; + } +} ``` ### **...** diff --git a/solution/0800-0899/0846.Hand of Straights/README_EN.md b/solution/0800-0899/0846.Hand of Straights/README_EN.md index 4b05df28185b6..3d90a2e1904e2 100644 --- a/solution/0800-0899/0846.Hand of Straights/README_EN.md +++ b/solution/0800-0899/0846.Hand of Straights/README_EN.md @@ -53,7 +53,33 @@ ### **Java** ```java - +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : hand) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + groupSize; i++) { + if (!mp.containsKey(i)) { + return false; + } + int time = mp.get(i); + if (time == 1) { + mp.remove(i); + } else { + mp.replace(i, time - 1); + } + } + } + return true; + } +} ``` ### **...** diff --git a/solution/0800-0899/0846.Hand of Straights/Solution.java b/solution/0800-0899/0846.Hand of Straights/Solution.java new file mode 100644 index 0000000000000..f86da00f5f736 --- /dev/null +++ b/solution/0800-0899/0846.Hand of Straights/Solution.java @@ -0,0 +1,27 @@ +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : hand) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + groupSize; i++) { + if (!mp.containsKey(i)) { + return false; + } + int time = mp.get(i); + if (time == 1) { + mp.remove(i); + } else { + mp.replace(i, time - 1); + } + } + } + return true; + } +} \ No newline at end of file