846. Hand of Straights, 1296. Divide Array in Sets of K Consecutive Numbers
use treeMap
T: O(nlogn*k)
S: O(n)
class Solution {
public boolean isPossibleDivide(int[] nums, int k) {
int n = nums.length;
if (n%k != 0) {
return false;
}
TreeMap<Integer, Integer> map = new TreeMap<>(); // num, count
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (int key : map.keySet()) {
if (map.get(key) > 0) {
for (int i = k - 1; i >= 0; i--) {
if (map.getOrDefault(key+i, 0) < map.get(key)) {
return false;
}
map.put(key + i, map.getOrDefault(key+i, 0) - map.get(key));
}
}
}
return true;
}
}
/*
sets of k consecutive numbers.
array is size k
Divide to one more array
use treeMap, sort and get freq map
[1,2,3,3,4,4,5,6]
after sort and get freq map
1 1 2 2 1 1 => count
1 2 3 4 5 6 => nums
[ ] k = 4
after subtract with nums[0] = 1
0 0 1 1 1 1
1 2 3 4 5 6
subtract with nums[2] = 1
0 0 1 1 1 1
1 2 3 4 5 6
[ ]
*/use hashmap + min, max value
T: O(n*k)
S: O(n)
HashMap + Sort
T: O(n + nlogn + n*k)
S: O(n)
Find Roots (amazing solution)
T: O(n)
S: O(n)
Last updated
Was this helpful?