diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md index d4d2efd864036..a7ce38e4b8eed 100644 --- a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md @@ -76,7 +76,33 @@ ```java - +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + if (nums.length % k != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : nums) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + k; 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/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md index 3e50413785515..6d50a731489ec 100644 --- a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md @@ -63,7 +63,33 @@ Return True if it is possible. Otherwise, return < ### **Java** ```java - +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + if (nums.length % k != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : nums) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + k; 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/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution.java b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution.java new file mode 100644 index 0000000000000..460138a2d38f8 --- /dev/null +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution.java @@ -0,0 +1,27 @@ +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + if (nums.length % k != 0) { + return false; + } + TreeMap mp = new TreeMap<>(); + for (int item : nums) { + mp.put(item, mp.getOrDefault(item, 0) + 1); + } + + while (mp.size() > 0) { + int start = mp.firstKey(); + for (int i = start; i < start + k; 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